package com.baichang.taoshunda.service.impl;

import cn.jpush.api.push.model.Message;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AppPay;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.util.AlipayUtil;
import com.baichang.framework.Constant;
import com.baichang.framework.excelption.ServiceException;
import com.baichang.framework.model.Page;
import com.baichang.framework.utils.*;
import com.baichang.taoshunda.dao.*;
import com.baichang.taoshunda.entity.*;
import com.baichang.taoshunda.entity.em.*;
import com.baichang.taoshunda.service.*;
import com.baichang.taoshunda.utils.*;
import com.baichang.taoshunda.weixin.tencent.WeixinUtils;
import com.common.utils.EmojiUtil;
import com.weixin.pay.api.InstantArrivalPay;
import com.weixin.pay.api.WeixinPay;
import com.weixin.pay.api.model.PayInfo;
import com.weixin.pay.api.model.WxConfig;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * Created by Administrator on 2017/8/17 0017.
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private UserService userService;

    @Autowired
    private DeliveryClerkService deliveryClerkService;


    @Autowired
    private PensionService pensionService;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private ShopCarDao shopCarDao;

    @Autowired
    private OrderStateDao orderStateDao;
    @Autowired
    private CouponDao couponDao;

    @Autowired
    private ParamsService paramsService;

    @Autowired
    private OrderDetailsReasonDao orderDetailsReasonDao;

    @Autowired
    private ReminderService reminderService;
    @Autowired
    private DeliveryblancceDao deliveryblancceDao;
    @Autowired
    private BalanceDetailsService balanceDetailsService;
    @Autowired
    private OrderDetailsDao orderDetailsDao;
    @Autowired
    private BussTypeDao bussTypeDao;
    @Autowired
    private ReservationOrderService reservationOrderService;

    @Autowired
    private ReservationOrderDao reservationOrderDao;
    @Autowired
    private UserRedHistoryDao userRedHistoryDao;
    @Autowired
    private TrendsDao trendsDao;
    @Autowired
    private FreezeOrderDao freezeOrderDao;
    @Autowired
    private GoodsSpecValueService goodsSpecValueService;
    @Autowired
    private RebateService rebateService;

    /**
     * 统计当前商家的当前月售
     *
     * @param bussId 商家编号
     * @return
     */
    @Override
    public int getCountByMouthAndBusssId(int bussId) {

        return orderDao.getCountByMouthAndBusssId(bussId);
    }

    /**
     * 根据状态获取商家订单
     *
     * @param bussId     商家编号
     * @param orderState 订单状态
     *                   2：待接单
     *                   3：待配送
     *                   4：退款/售后
     *                   5：进行中
     *                   6：已完成
     *                   10：配送中
     *                   0：全部
     * @param date       日期
     * @param endDate
     * @param nowPage
     * @param pageSize   @return
     */
    @Override
    public List<Map<String, Object>> findBusinessOrderByState(Integer bussId, Integer orderState, String date, String endDate, Integer nowPage, int pageSize) {
        List<Map<String, Object>> maps = orderDao.findBusinessOrderByState(bussId, orderState, date, endDate, nowPage, pageSize);
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
        if (maps != null && maps.size() > 0) {
            getOrderListMap(maps, returnMaps);
        }
        return groupByDateList(returnMaps, "created");
    }

    private List<Map<String, Object>> getOrderListMap(List<Map<String, Object>> maps, List<Map<String, Object>> returnMaps) {
        for (Map<String, Object> map : maps) {
            Integer orderId = ConvertTypeUtils.obj2Integer(map.get("id"));
            String orderNumber = map.get("orderNumber").toString();
            List<Map<String, Object>> orderDetails = orderDetailsDao.findOrderDetailsByOrderNumber(orderNumber);
            map.put("orderDetails", orderDetails);
            //是否催单
            Integer isReminder = reminderService.checkBussinessIsReminder(orderId);
            Reminder reminder = reminderService.getReminderByOrderId(orderId);
            Integer remindId = 0;
            if (reminder != null) {
                remindId = reminder.getId();
            }
            if (map.get("refunds").toString().equals("1")) {
                FreezeOrder freezeOrder = freezeOrderDao.getFreezeOrderByOrderNumber(orderNumber);
                if (freezeOrder != null) {
                    map.put("isDeleteStatus", 0);
                } else {
                    map.put("isDeleteStatus", 1);
                }
            } else {
                map.put("isDeleteStatus", 1);
            }
            map.put("remindId", remindId);
            map.put("isReminder", isReminder);
            returnMaps.add(map);
        }
        return returnMaps;
    }

    private List<Map<String, Object>> groupByDateList(List<Map<String, Object>> mapList, String key) {
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
        if (mapList != null && mapList.size() > 0) {
            List<String> dates = new ArrayList<String>();
            for (Map<String, Object> map : mapList) {
                Date date = ConvertTypeUtils.obj2DateTime(map.get(key));
                String dateStr = DateUtil.formatDate(date, DateUtil.DATE_FORMAT);
                if (!dates.contains(dateStr)) {
                    dates.add(dateStr);
                }
            }
            if (dates != null && dates.size() > 0) {
                for (String str : dates) {
                    Map<String, Object> dateMap = new HashMap<String, Object>();
                    dateMap.put("date", str);
                    List<Map<String, Object>> maps = new ArrayList<>();
                    for (Map<String, Object> map : mapList) {
                        Date date = ConvertTypeUtils.obj2DateTime(map.get(key));
                        String dateStr = DateUtil.formatDate(date, DateUtil.DATE_FORMAT);
                        if (dateStr.equals(str)) {
                            maps.add(map);
                        }
                    }
                    dateMap.put("orders", maps);
                    returnMaps.add(dateMap);
                }
            }
        }
        return returnMaps;
    }

    /**
     * 根据状态获取商家订单
     *
     * @param bussId     商家编号
     * @param orderState 订单状态
     *                   2：待接单
     *                   3：待配送
     *                   4：退款/售后
     *                   5：进行中
     *                   6：已完成
     *                   10：配送中
     *                   0：全部
     * @param date       日期
     * @param endDate
     * @param nowPage
     * @param pageSize   @return
     */
    @Override
    public List<Map<String, Object>> findBusinessHomeOrderByState(Integer bussId, Integer orderState, String date, String endDate, Integer nowPage, int pageSize) {
        List<Map<String, Object>> maps = orderDao.findBusinessOrderByState(bussId, orderState, date, endDate, nowPage, pageSize);
//        maps = EmojiUtil.returnEmojiList(maps, "remark", "remark");
        List<Map<String, Object>> returnMaps = new ArrayList<Map<String, Object>>();
//        if (maps != null && maps.size() > 0) {
//
//            for (Map<String, Object> map : maps) {
//                Integer orderId = ConvertTypeUtils.obj2Integer(map.get("id"));
//                String orderNumber = map.get("orderNumber").toString();
//                List<Map<String, Object>> orderDetails = orderDetailsDao.findOrderDetailsByOrderNumber(orderNumber);
//                map.put("orderDetails", orderDetails);
//                //是否催单
//                Integer isReminder = reminderService.checkBussinessIsReminder(orderId);
//                Reminder reminder = reminderService.getReminderByOrderId(orderId);
//                Integer remindId = 0;
//                if (reminder != null) {
//                    remindId = reminder.getId();
//                }
//                map.put("remindId", remindId);
//                map.put("isReminder", isReminder);
//                returnMaps.add(map);
//            }
//        }
        return getOrderListMap(maps, returnMaps);
    }

    /**
     * 商家拒绝接单
     *
     * @param orderNumber  订单编号
     * @param singleReason
     * @return
     */
    @Override
    public boolean businessRefuseTaking(String orderNumber, String singleReason) throws ServiceException {
        //判断订单状态
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!order.getOrderState().equals(OrderState.待接单.getCode())) {
            throw new ServiceException("当前订单状态不允许拒绝接单");
        }
        orderDao.updateSingleReason(order.getId(), singleReason);
        //修改订单状态
        //获取用户信息
        User user = userService.getUserBeanById(order.getBuyerId());
        String title = "您的订单已被商家拒绝接单";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pushType", PushType.订单.getCode());
        map.put("orderType", order.getOrderType() + "");
        map.put("orderNumber", order.getOrderNumber());
        JSONObject jsonObject = JSONObject.fromObject(map);
        //消息推送
        JPushUtils.sendByAlias(title, title, jsonObject.toString(), user.getAccount());
        //原路退款
        returnMoney(order.getPayType(), order, OrderState.拒绝接单.getCode(), 0, 0);
        //添加用户账单
        balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.拒绝接单.getCode(), order.getOrderNumber());
        return updateOrderState(OrderState.拒绝接单, BackOrderState.未退款, order.getId());
    }

    private void returnMoney(Integer payType, Order order, Integer orderState, Integer goodsId, Integer stock) throws ServiceException {
        BigDecimal redMoney = order.getRedPacketMoney();
        //1 判断支付方式
        //2 查看支付金额、订单号
        //3 取出金额返回账户（1支付宝、2微信  0红包折扣   3支付宝加红包抵扣   4 ）
        boolean isTrue = false;
        Double returnMoney = 0.00;
        double bili = 1;
        User user = userService.getUserBeanById(order.getBuyerId());
        if (order.getOrderState().equals(OrderState.待取货.getCode()) || order.getOrderState().equals(OrderState.待接单.getCode())
                || order.getOrderState().equals(OrderState.待配送.getCode()) || order.getOrderState().equals(OrderState.配送中.getCode())) {
            if (order.getOrderType() == 1 || order.getOrderType() == 3) {
                returnMoney = order.getReturnMoney().doubleValue();
            } else if (order.getOrderType().equals(2)) {
                //预约单所有的商品总数
                int allCount = reservationOrderService.getCountByOrder(order.getOrderNumber());
                //未使用的商品数量
                int count = reservationOrderService.getCountByOrderAndState0(order.getOrderNumber());
                System.out.println("getAllMoney" + order.getAllMoney());
                //查询所有的商品的总金额
                BigDecimal allmoney = orderDetailsDao.getAllMoney(order.getOrderNumber());
                //所有退还金额
                //比较商品是否修改价格  等于0就是没有修改价格没有参与满减
                if (order.getGoodsAllMoney().compareTo(allmoney) == 0) {
                    returnMoney = reservationOrderDao.getReturnMoney(order.getOrderNumber());
                } else {
                    //计算出来的所有的退款金额
                    returnMoney = reservationOrderDao.getReturnMoney(order.getOrderNumber());
                    bili = BigDecimal.valueOf(returnMoney).divide(allmoney, 2, BigDecimal.ROUND_DOWN).doubleValue();
                    returnMoney = order.getAllMoney().multiply(BigDecimal.valueOf(bili)).doubleValue();
                }

//                returnMoney = order.getAllMoney().divide(BigDecimal.valueOf(allCount), 2, BigDecimal.ROUND_DOWN).doubleValue() * count;

                double returnPlatMoney = order.getPlatformGetMoney().divide(BigDecimal.valueOf(allCount), 2,
                        BigDecimal.ROUND_DOWN).doubleValue() * count;
                double platMoney = order.getPlatformGetMoney().doubleValue() - returnPlatMoney;
                System.out.println("returnMoney" + returnMoney);
                if (returnMoney >= 0) {
                    System.out.println("order.getAllMoney().doubleValue() - returnMoney " + ((order.getAllMoney().doubleValue()) - returnMoney));
                    businessService.updateBussinessBalance(order.getSellerId(), MathUtils.sub(order.getAllMoney()
                            .doubleValue(), returnMoney, platMoney), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());
                }
                if (allCount != count) {
                    if (user != null) {
                        if (user.getIsCertificate() == 1) {
                            OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(), 1);
                            int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
                            String goodsName = "";
                            if (number > 1) {
                                goodsName = orderdetail.getGoodsName() + "等多件商品";
                            } else {
                                goodsName = orderdetail.getGoodsName();
                            }
                            pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
                                    (order.getGoodsAllMoney().subtract(BigDecimal.valueOf(returnMoney))).divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), (order.getGoodsAllMoney().subtract(BigDecimal.valueOf(returnMoney))),
                                    (order.getGoodsAllMoney().subtract(BigDecimal.valueOf(returnMoney))).divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
                                    order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney(), orderdetail.getGoodsId());

                        }
                    }
                }
                reservationOrderService.updateOrderState(order.getOrderNumber());
            }
        } else {
            returnMoney = MathUtils.sub(order.getAllMoney().doubleValue(), order.getDispatching().doubleValue(), order.getFee().doubleValue());
            if (returnMoney - order.getReturnMoney().doubleValue() > 0) {
                redMoney = BigDecimal.valueOf(returnMoney).subtract(order.getReturnMoney());
                returnMoney = order.getReturnMoney().doubleValue();
                System.out.println("ssssssssssssssssssssssssssssss" + redMoney + ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>" + returnMoney);
            } else {
                redMoney = BigDecimal.valueOf(0);
            }
        }
        System.out.println(order.getRedPacketMoney());
        System.out.println("红包金额" + redMoney);
        //除去红包的支付金额小于所有的退款金额，那么红包金额就是所有的退款金额减去除去红包的支付金额的差
        if (order.getReturnMoney().doubleValue() <= returnMoney && returnMoney != 0) {
            redMoney = order.getAllMoney().subtract(order.getReturnMoney()).subtract(order.getFee()).subtract(order.getDispatching());
            returnMoney = order.getReturnMoney().doubleValue();
        } else if (returnMoney == 0) {
            //如果所有的退款金额小于出去红包的支付金额，那么退款金额是就是returnMoney不变！红包金额为0
            redMoney = order.getRedPacketMoney();
            returnMoney = 0D;
            System.out.println("returnMoney" + returnMoney);
            System.out.println("" + order.getAllMoney().subtract(BigDecimal.valueOf(returnMoney)));
        } else {
            redMoney = order.getAllMoney().subtract(order.getReturnMoney());
        }
        if (order.getRedPacketMoney().doubleValue() > 0) {
            System.out.println("红包金额  user.getRedPacket()" + user.getRedPacket());
            System.out.println("红包金额 user.getRedPacket().add(redMoney)" + user.getRedPacket().add(redMoney));
            user.setRedPacket(user.getRedPacket().add(redMoney));
            userService.updateUser(user);

        }
        System.out.println("returnMoney    end" + returnMoney);
        BigDecimal bigReturnMoney = new BigDecimal(returnMoney);
        bigReturnMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        //1支付宝、2微信
        if (payType == 1 || payType == 3) {
//            isTrue = AlipayUtil.refundMoney(order.getPayOrderkid(), order.getAllMoney().doubleValue());
            isTrue = AlipayUtil.refundMoney(order.getPayOrderkid(), bigReturnMoney.doubleValue());
        } else if (payType == 2 || payType == 4) {
//            isTrue = WeixinUtils.payMallRefund(order.getPayOrderkid(), order.getAllMoney().multiply(new BigDecimal(100)).intValue(), order.getAllMoney().multiply(new BigDecimal(100)).intValue());
            isTrue = WeixinUtils.payMallRefund(order.getPayOrderkid(), (int) MathUtils.mul(order.getReturnMoney().doubleValue(), 100D), (int) MathUtils.mul(bigReturnMoney.doubleValue(), 100D));
        }

//        //申请退款的时候才修改库存
//        if (orderState == 9) {
//            goodsDao.updateSaleNum(goodsId, stock);
//        }
    }

    /**
     * 商家接单
     *
     * @param orderNumber 订单编号
     * @return
     */
    @Override
    public boolean businessTaking(String orderNumber) throws ServiceException {
        //判断订单状态
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!order.getOrderState().equals(OrderState.待接单.getCode())) {
            throw new ServiceException("当前订单状态不允许接单");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        if (bussiness.getState() == 0) {
            throw new ServiceException("您已被禁用不能进行接单，如有疑问请联系客服！");
        }
        //修改订单状态
        OrderState orderState;
        if (order.getDispatching().compareTo(BigDecimal.valueOf(0)) == 0) {
            if (order.getOrderType() == 3) {
                orderState = OrderState.等待用户自提;
            } else {
                orderState = OrderState.配送中;
            }

        } else {
            orderState = OrderState.待配送;
        }
//        if (order.getOrderType() == 3) {
//            orderStateDao.updateIsSelfIntroduction(orderNumber, 1);
//        }
//        companyBalanceService.saveCompanyBalance(order, bussiness);
        //获取用户信息
        User user = userService.getUserBeanById(order.getBuyerId());
        String title = "您的订单已被商家接单";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pushType", PushType.订单.getCode());
        map.put("orderType", order.getOrderType() + "");
        map.put("orderNumber", order.getOrderNumber());
        JSONObject jsonObject = JSONObject.fromObject(map);
        //消息推送
        JPushUtils.sendByAlias(title, title, jsonObject.toString(), user.getAccount());
        //添加线程池异步处理，不影响主业务的运行速度
        final String lat = bussiness.getLat();
        final String lng = bussiness.getLng();
        final Integer cityId = bussiness.getCityId();
        final Integer orderId = order.getId();
        if (order.getDispatching().compareTo(BigDecimal.valueOf(0)) > 0) {
            Constant.scheduledExecutorService.schedule(new Runnable() {
                @Override
                public void run() {
                    try {
                        pushAreaDelivery(lat, lng, cityId, orderId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, 1, TimeUnit.SECONDS);
        }
        return updateOrderState(orderState, BackOrderState.未退款, order.getId());
    }

    /**
     * 推送给范围内的配送员
     *
     * @return
     */
    private boolean pushAreaDelivery(String lat, String lng, Integer cityId, Integer orderId) {
        //推送给范围内的配送员
        System.out.println(">>>>>>>>>>>>>>>>>>>>>>" + "进入推送配送");
        List<String> deliveryRedisKey = DeliveryUtils.getAllDeliveryRedisKey("*delivery*");
        System.out.println("查询所有的配送员编号" + deliveryRedisKey + "时间" + new Date());
        Map getValue = paramsService.getParamsValue(26, 24);
        List<Integer> deliveryIds = DeliveryUtils.getAreaDelivery(deliveryRedisKey, lat, lng, cityId, ConvertTypeUtils.obj2Double(getValue.get("value")));
        System.out.println("deliveryIds所有符合的配送员" + deliveryIds);
        if (deliveryIds.size() > 0) {
            List<String> deliveryAccounts = deliveryClerkService.getDeliveryClerkAccountsByIds(deliveryIds);
            Map<String, String> data = new HashMap<>();
            //透传
            DeliveryJpushUtils.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(data).build(), deliveryAccounts);
            UserPushMsgUtil.newOrderPush(orderId, deliveryAccounts, 1);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 商家同意退款
     *
     * @param orderNumber 订单编号
     * @return
     */
    @Override
    public boolean businessAgreeBack(String orderNumber) throws ServiceException {
        //判断订单状态
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!Objects.equals(order.getBackOrderState(), BackOrderState.申请退款.getCode())) {
            throw new ServiceException("当前订单状态不允许同意退款");
        }
//        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        //修改订单状态
//        boolean bl = orderDao.updateOrderStateByOrderNumber(orderNumber, OrderState.同意退款.getCode()) > 0;
//        balanceDetailsService.saveReturnMoney(order, UserBalanceState.退款.getCode());
//        companyBalanceService.saveReturnMoney(order, bussiness);
        //获取用户信息
        User user = userService.getUserBeanById(order.getBuyerId());
        //添加用户账单
        balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.退款.getCode(), order.getOrderNumber());
        String title = "您的退款商家已同意";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pushType", PushType.订单.getCode());
        map.put("orderType", order.getOrderType() + "");
        map.put("orderNumber", order.getOrderNumber());
        JSONObject jsonObject = JSONObject.fromObject(map);
        //消息推送
        JPushUtils.sendByAlias(title, title, jsonObject.toString(), user.getAccount());
//        if (order.getDisId() != 0 && null != order.getDisId()) {
//            DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(order.getDisId());
//            if (deliveryClerk != null) {
//                String distitle = "您的订单" + order.getOrderNumber() + "商家同意退款";
//                UserJPushHelper jPushHelper = new UserJPushHelper("distribution.properties");
//                jPushHelper.sendByAlias(distitle, distitle, jsonObject.toString(), deliveryClerk.getAccount(), "");
//            }
//        }
        //原路退款
        if (order.getDispatching().compareTo(BigDecimal.valueOf(0)) != 0) {
            if (Objects.equals(order.getOrderState(), OrderState.配送中.getCode()) || Objects.equals(order.getOrderState(), OrderState.待取货.getCode())) {
                DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(order.getDisId());
                if (deliveryClerk != null) {
                    UserPushMsgUtil.returnMoneyOrderPushByOrderStateToDelivery(order.getId(), order.getBuyerId(), deliveryClerk.getAccount(), orderNumber, order.getOrderType(), order.getOrderState(), order.getReasonRefund());
                }

            }
        }
        returnMoney(order.getPayType(), order, OrderState.同意退款.getCode(), 0, 0);
        //手机端根据未退款来判断退款状态
        //当退款状态是未退款时，手机端展示订单状态
        return updateOrderState(OrderState.同意退款, BackOrderState.未退款, order.getId());
    }

    /**
     * 商家拒绝退款
     *
     * @param orderNumber 订单编号
     * @return
     */
    @Override
    public boolean businessRefuseBack(String orderNumber, String reason) throws ServiceException {
        //判断订单状态
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!Objects.equals(order.getBackOrderState(), BackOrderState.申请退款.getCode())) {
            throw new ServiceException("当前订单状态不允许同意退款");
        }
        //修改订单状态
//        boolean bl = orderDao.updateOrderStateByOrderNumber(orderNumber, OrderState.拒绝退款.getCode()) > 0;
//        updateOrderBackState(order.getId(), BackOrderState.拒绝退款);
        //获取用户信息
        User user = userService.getUserBeanById(order.getBuyerId());
        String title = "您的退款商家未同意";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pushType", PushType.订单.getCode());
        map.put("buyerId", order.getBuyerId());
        map.put("orderNumber", orderNumber);
        map.put("reason", reason);
        JSONObject jsonObject = JSONObject.fromObject(map);
        //消息推送
        JPushUtils.sendByAlias(title, title, jsonObject.toString(), user.getAccount());
        //原路退款
        //1 判断支付方式
        //2 查看支付金额、订单号
        //3 取出金额返回账户（1支付宝、2微信）
//        if (order.getOrderState() == 8) {
//            //1支付宝、2微信
//            if (order.getPayType() == 1) {
//                AlipayUtil.refundMoney(order.getPayOrderkid(), order.getAllMoney().doubleValue());
//            } else {
//                WeixinUtils.payMallRefund(order.getPayOrderkid(), order.getAllMoney().multiply(new BigDecimal(100)).intValue(), order.getAllMoney().multiply(new BigDecimal(100)).intValue());
//            }
//        }
        //修改订单的拒单理由
        orderDao.updateOrderReason(order.getId(), reason);
        return updateOrderBackState(order.getId(), BackOrderState.拒绝退款);
    }

    /**
     * 查看订单详情
     *
     * @param orderNumber 订单编号
     * @return
     */
    @Override
    public Map<String, Object> getOrderDetail(String orderNumber) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        User user = userService.getUserBeanById(order.getBuyerId());
        int extraction = orderDetailsDao.getExtraction(order.getId());
        //订单信息
        map.put("orderId", order.getId());
        map.put("orderNumber", order.getOrderNumber());
        map.put("userName", order.getName());
        map.put("address", order.getGoodsAdress());
        map.put("receiverPhone", order.getReceiverPhone());
        map.put("created", order.getCreated());
        map.put("extraction", extraction);
        map.put("invoiceHead", order.getInvoiceHead());
        map.put("invoiceNumber", order.getInvoiceNumber());
        map.put("reasonImg", order.getReasonImg());
        map.put("redPacketMoney", order.getRedPacketMoney());
        map.put("returnMoney", order.getReturnMoney());
        map.put("reasonRefund", order.getReasonRefund());
        map.put("barterImg", order.getBarterImg());
        map.put("barterReason", order.getBarterReason());
        map.put("allMoney", order.getAllMoney());
        map.put("subMoney", order.getSubMoney());
        map.put("headPic", user.getHeadPic());
        map.put("singleReason", order.getSingleReason());
        map.put("goodsAllMoney", order.getGoodsAllMoney());
        map.put("companyRyId", JSONObject.fromObject(bussiness.getRyToken()).get("userId"));
        map.put("remark", order.getRemark());
//        try {
//            map.put("remark", EmojiUtil.emojiRecovery2(order.getRemark()));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        map.put("reason", order.getReason());
        map.put("orderState", order.getOrderState());
        map.put("backOrderState", order.getBackOrderState());
        map.put("uLat", order.getUlat());
        map.put("orderType", order.getOrderType());
        map.put("uLng", order.getUlng());
        map.put("companyLat", bussiness.getLat());
        map.put("companyLng", bussiness.getLng());
        map.put("dispatching", order.getDispatching());
        map.put("backOrderState", order.getBackOrderState());
        map.put("bussGetMoney", order.getBussGetMoney());
        map.put("isReturnGoods", orderDao.getIsReturnGoods(order.getId()));
        map.put("isRemind", reminderService.checkBussinessIsReminder(order.getId()));
        Reminder reminder = reminderService.getReminderByOrderId(order.getId());
        Integer remindId = 0;
        if (reminder != null) {
            remindId = reminder.getId();
        }
        map.put("remindId", remindId);
        //骑手信息
        Integer disId = order.getDisId();
        try {
            DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
            map.put("disHeadPic", deliveryClerk.getHeadPic());
            map.put("disName", deliveryClerk.getName());
            map.put("disPhone", deliveryClerk.getAccount());
            map.put("disId", deliveryClerk.getId());
            //获取配送员的经纬度的key值   city4delivery8
            String redisKey = "city" + bussiness.getCityId() + "delivery" + disId;
            //获取redis里面保存的值
            String redisCode = RedisUtil.get(redisKey);
            //解析值
            if (redisCode != null && !redisCode.isEmpty()) {
                JSONObject jsonObject = JSONObject.fromObject(redisCode);
                map.put("dislng", Double.valueOf(jsonObject.get("lng").toString()));
                map.put("dislat", Double.valueOf(jsonObject.get("lat").toString()));
            } else {
                map.put("dislng", "");
                map.put("dislat", "");
            }
        } catch (Exception e) {
            map.put("disHeadPic", "");
            map.put("disName", "");
            map.put("disPhone", "");
            map.put("disId", "");
            map.put("dislng", "");
            map.put("dislat", "");
        }
        //订单详情
        List<Map<String, Object>> orderDetails = orderDetailsDao.findOrderDetailsByOrderNumber(orderNumber);
        map.put("orderDetails", orderDetails);
        //商家信息
        map.put("busHeadPic", bussiness.getHeadPic());
        map.put("busName", bussiness.getBussName());
        map.put("busId", bussiness.getId());
        return map;
    }

    /**
     * 提交订单
     *
     * @param goods          商品信息
     * @param userId         用户编号
     * @param bussId         商家编号
     * @param bussName       商家名称
     * @param payType        支付类型
     * @param userNmae       收货人
     * @param goodsAddress   收货地址
     * @param phone          收货人电话
     * @param remak          备注
     * @param fee            小费
     * @param dispatching    配送费
     * @param goodsMoney     商品总价
     * @param allMoney       所有价格
     * @param ulng           经度
     * @param ulat           纬度
     * @param deliveryTime   计划配送时间
     * @param subMoney       优惠金额
     * @param invoiceHead
     * @param invoiceNumber  @return
     * @param redPacketMoney
     * @param returnMoney
     * @param isActivity
     * @param orderType
     */
    @Override
    public Map<String, Object> submintOrder(String goods, int userId, int bussId, String bussName, int payType, String userNmae, String goodsAddress, String phone, String remak, double fee, double dispatching, double goodsMoney, double allMoney, double ulng, double ulat, String deliveryTime, double subMoney, String invoiceHead, String invoiceNumber, double redPacketMoney, double returnMoney, int isActivity, int orderType) throws ServiceException {
        if (checkGoodsMoney(goods, goodsMoney)) {
            try {
                synchronized (this) {
                    if (redPacketMoney > 0) {
                        User user = userService.getUserBeanById(userId);
                        if (user.getRedPacket().compareTo(BigDecimal.valueOf(redPacketMoney)) >= 0) {
                            user.setRedPacket(user.getRedPacket().subtract(BigDecimal.valueOf(redPacketMoney)));
                            userService.updateUser(user);
                        } else {
                            throw new ServiceException("红包余额不足！");
                        }
                    }
                }
                Map<String, Object> map = new HashedMap();
                boolean flag = false;
                boolean isNoReasonReturn = false;
                boolean isHomeInstallation = false;
                String orderKid = KidUtils.getKKid();
                String payOrderKid = "payOrder" + KidUtils.getKid();
                //创建订单
                Order order = new Order();
                //添加所有费用
                order.setAllMoney(BigDecimal.valueOf(allMoney));
                //添加商品费用
                order.setGoodsAllMoney(BigDecimal.valueOf(goodsMoney));
                //下单时间
                order.setCreated(new Date());
                //买家编号
                order.setBuyerId(userId);
                //配送费
                order.setDispatching(BigDecimal.valueOf(dispatching));
                //商家编号
                order.setSellerId(bussId);
                order.setUserStatus(1);
                order.setCompanyStatus(1);
                //获取商家信息
                Bussiness bussiness = businessService.getBusinessById(bussId);
                //计算距离
                double distace = Spatial4jUtil.getDistance(ulng, ulat, Double.parseDouble(bussiness.getLng()), Double.parseDouble(bussiness.getLat()));
                //距离
                order.setDistance(distace);
                //用户的经纬度
                order.setUlng(ulng);
                order.setCompanyIsSure(0);
                //保存优惠金额
                order.setSubMoney(BigDecimal.valueOf(subMoney));
                order.setUlat(ulat);
                order.setInvoiceHead(invoiceHead);
                order.setInvoiceNumber(invoiceNumber);
                //商家名称
                order.setOrderName(bussName);
                //支付单号
                order.setPayOrderkid(payOrderKid);
                //小费
                order.setFee(BigDecimal.valueOf(fee));
                //订单号
                order.setOrderNumber(orderKid);
                order.setRemark(remak);
                order.setBackOrderState(BackOrderState.未退款.getCode());
                //收货地址
                order.setGoodsAdress(goodsAddress);
                //是否支持无理由退货
                order.setRefunds(2);
                //收货人电话
                order.setReceiverPhone(phone);
                order.setRedPacketMoney(BigDecimal.valueOf(redPacketMoney));
                order.setReturnMoney(BigDecimal.valueOf(returnMoney));
                order.setIsActivity(isActivity);
                order.setOrderState(OrderState.待付款.getCode());
                //支付方式
                order.setPayType(0);
                order.setOrderType(orderType);
                double choucheng = Double.parseDouble(bussTypeDao.getEntityById(bussiness.getBussTypeId()).getProportionate());
                double chouchngMoney = goodsMoney * choucheng / 100;
                BigDecimal platformGetMoney = new BigDecimal(chouchngMoney);
                double dplatformGetMoney = platformGetMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
                //添加商家预计收入
                order.setBussGetMoney(BigDecimal.valueOf(goodsMoney - dplatformGetMoney));
                //添加平台抽成的钱
                order.setPlatformGetMoney(platformGetMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
                //收货人
                order.setName(userNmae);
                if (!deliveryTime.isEmpty() || !deliveryTime.equals("")) {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date date = sdf.parse(deliveryTime);
                    order.setPlannedDeliveryTime(date);
                }
                int orderId = (int) orderDao.save(order);
                if (orderType != 1) {
                    userService.updateInviteAccount(userId, phone);
                }
                if (orderId > 0) {
                    map.put("orderKid", orderKid);
                    map.put("payMoney", returnMoney);
                    JSONArray jsonArray = JSONArray.fromObject(goods);
                    //添加订单明细
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject object = JSONObject.fromObject(jsonArray.get(i));
                        OrderDetails orderDetails = new OrderDetails();
                        orderDetails.setCreated(new Date());
                        orderDetails.setOrderNumber(orderKid);
                        int goodsId = Integer.parseInt(object.get("goodsId").toString());
                        int number = Integer.parseInt(object.get("goodsNumber").toString());
                        orderDetails.setCount(number);
                        orderDetails.setStatus(1);
                        orderDetails.setIsReturn(0);
                        orderDetails.setGoodsId(goodsId);
                        orderDetails.setGoodsName(object.get("goodsName").toString());
                        orderDetails.setUnit(object.get("goodsUnit").toString());
                        orderDetails.setGoodsSpec(object.get("goodsSpec").toString());
                        orderDetails.setIsFree(Integer.parseInt(object.get("isFree").toString()));
                        orderDetails.setIsBespeak(Integer.parseInt(object.get("isBespeak").toString()));
                        orderDetails.setIsNoReasonReturn(Integer.parseInt(object.get("isNoReasonReturn").toString()));
                        if (Integer.parseInt(object.get("isHomeInstallation").toString()) == 1) {
                            isHomeInstallation = true;
                        }
                        if (Integer.parseInt(object.get("isNoReasonReturn").toString()) == 1) {
                            isNoReasonReturn = true;
                        }

                        orderDetails.setUnivalent(BigDecimal.valueOf(Double.parseDouble(object.get("goodsPrice").toString())));
                        flag = orderDetailsDao.save(orderDetails) > 0;
                    }
                    //是否退货
                    if (isNoReasonReturn) {
                        orderDao.updateOrderRefunds(orderId);
                    } //是否上门安装
                    if (isHomeInstallation) {
                        orderDao.updateIsHomeInstallation(orderId);
                    }
                    //添加完成删除购物车
                    if (flag) {
                        shopCarDao.deleteShopCarByBussId(userId, bussId);
                    }
                    if (redPacketMoney == allMoney) {
                        balanceDetailsService.saveBalanceDetail(order.getOrderNumber());
                        JSONObject object = JSONObject.fromObject(order);
                        Map<String, String> pushMap = object;
                        pushMap.put("orderType", order.getOrderType() + "");
                        UserJPushHelper companyJPushHelper = new UserJPushHelper("business.properties");
                        companyJPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(pushMap).build(), bussiness.getAccount());
                        UserPushMsgUtil.sumbitOrderPush(order.getId(), order.getBuyerId(), bussiness.getAccount(), order.getOrderNumber(), order.getOrderType());
                        updateOrderState(OrderState.待接单, BackOrderState.未退款, orderId);
                        UserRedHistory userRedHistory = new UserRedHistory();
                        userRedHistory.setAllMoney(BigDecimal.valueOf(allMoney));
                        userRedHistory.setRedMoney(BigDecimal.valueOf(redPacketMoney));
                        userRedHistory.setCreated(new Date());
                        userRedHistory.setOrderNumber(orderKid);
                        userRedHistory.setType("普通订单消费");
                        userRedHistoryDao.save(userRedHistory);
                    } else {
                        updateOrderState(OrderState.待付款, BackOrderState.未退款, orderId);
                    }
                }
                return map;

            } catch (ParseException e) {
                throw new ServiceException("下单失败");
            }
        }
        return new HashedMap();
    }

    private boolean checkGoodsMoney(String goods, double goodsMoney) throws ServiceException {
        JSONArray jsonArray = JSONArray.fromObject(goods);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject goodsDetail = JSONObject.fromObject(jsonArray.get(i));
            //获取商品编号
            int goodsId = Integer.parseInt(goodsDetail.get("goodsId").toString());
            BigDecimal goodsPrice = BigDecimal.valueOf(Double.parseDouble(goodsDetail.get("goodsPrice").toString()));
            String goodsSpec = goodsDetail.get("goodsSpec").toString();
            JSONArray goodsSpecDetail = JSONArray.fromObject(goodsSpec);
            //判断商品是否存在规格
            Goods goodsBean = goodsDao.getGoodsById(goodsId);
            if (goodsBean == null || goodsBean.getIsUpper() != 1 || goodsBean.getStatus() != 1) {
                throw new ServiceException("该商品已被商家删除或下架！");
            }
            if (goodsSpecDetail.size() > 0) {
                //存在规格比较对应的规格的价格  [{"price":"0","specName":"商品分类","specValues":"黑色"},{"price":"0.1","specName":"规格","specValues":"L"}]
                Double specPrice = 0.0;
                String specValues = "";
                for (int g = 0; g < goodsSpecDetail.size(); g++) {
                    JSONObject jsonObject = JSONObject.fromObject(goodsSpecDetail.get(g));
                    //对应规格的价格
                    System.out.println(jsonObject.get("specName").toString());
                    if ("规格".equals(jsonObject.get("specName").toString())) {
                        System.out.println("规格    " + jsonObject.get("specName").toString());
                        specPrice = Double.parseDouble(jsonObject.get("price").toString());
                        System.out.println("规格    " + jsonObject.get("price").toString());
                        specValues = jsonObject.get("specValues").toString();
                    }

                }

                //查询对应商品的规格的价格
                double specPriceMoney = goodsSpecValueService.getPriceBySpecAndGoodsId(goodsId, specValues);
                if (specPrice != specPriceMoney) {
                    throw new ServiceException("商品出现变更请查看");
                }
//                else {
//                    goodsMoney2 = goodsMoney2 + specPriceMoney * number;
//                }
            } else {
                //不存在规格比较商品的金额
                //比较两个商品的单价
                if (goodsBean.getPrice().compareTo(goodsPrice) != 0) {
                    throw new ServiceException("商品出现变更请查看");
                }
//                else {
//                    goodsMoney2 = goodsMoney2 + goodsBean.getPrice().doubleValue() * number;
//                }
            }

        }

        return true;
    }

    /**
     * 查询订单
     * 武圣路
     * 接口
     * 用户端
     *
     * @param orderState 订单状态
     * @param userId     用户编号
     * @param nowPage    当前页
     * @param pageSize   条数
     * @return
     */
    @Override
    public List<Map<String, Object>> getOrderList(Integer orderState, Integer userId, Integer nowPage, Integer pageSize) {
        List<Map<String, Object>> orderList = orderDao.getOrderList(orderState, userId, nowPage, pageSize);
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).put("goods", orderDetailsDao.findOrderDetailsByOrderNumber(orderList.get(i).get("orderNumber").toString()));
        }
        return orderList;
    }

    @Override
    public Map<String, Object> getOrderDetialsByOrderNumber(String orderNumber) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        //商家信息
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        //订单信息
        map.put("orderId", order.getId());
        map.put("orderNumber", order.getOrderNumber());
        map.put("userName", order.getName());
        map.put("invoiceHead", order.getInvoiceHead());
        map.put("invoiceNumber", order.getInvoiceNumber());
        map.put("reasonImg", order.getReasonImg());
        map.put("barterImg", order.getBarterImg());
        map.put("orderType", order.getOrderType());
        map.put("barterReason", order.getBarterReason());
        map.put("applyReturnTime", order.getApplyReturnTime());
        map.put("companyRyId", JSONObject.fromObject(bussiness.getRyToken()).get("userId"));
        map.put("reasonRefund", order.getReasonRefund());
        map.put("address", order.getGoodsAdress());
        map.put("receiverPhone", order.getReceiverPhone());
        map.put("created", order.getCreated());
        map.put("remark", order.getRemark());
        map.put("allMoney", order.getAllMoney());
        map.put("returnMoney", order.getReturnMoney());
        map.put("reason", order.getReason());
        map.put("redPacketMoney", order.getRedPacketMoney());
        map.put("singleReason", order.getSingleReason());
        map.put("subMoney", order.getSubMoney());
        map.put("dispatching", order.getDispatching());
        map.put("plannedDeliveryTime", order.getPlannedDeliveryTime());
        map.put("backOrderState", order.getBackOrderState());
        map.put("fee", order.getFee());
        map.put("state", order.getOrderState());
        map.put("refunds", order.getRefunds());
        //骑手信息
        Integer disId = order.getDisId();
        DeliveryClerk deliveryClerk = null;
        if (order.getOrderState() == 3 || order.getOrderState() == 12 || order.getOrderState() == 4) {
            if (disId != null) {
                deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
                map.put("disHeadPic", deliveryClerk.getHeadPic());
                map.put("disName", deliveryClerk.getName());
                map.put("disPhone", deliveryClerk.getAccount());
                map.put("disId", deliveryClerk.getId());
                //获取配送员的经纬度的key值
                String redisKey = "city" + bussiness.getCityId() + "delivery" + disId;
                //获取redis里面保存的值
                String redisCode = RedisUtil.get(redisKey);
                //解析值
                if (redisCode != null) {
                    JSONObject jsonObject = JSONObject.fromObject(redisCode);
                    map.put("dislng", Double.valueOf(jsonObject.get("lng").toString()));
                    map.put("dislat", Double.valueOf(jsonObject.get("lat").toString()));
                } else {
                    map.put("dislng", "");
                    map.put("dislat", "");
                }

            }
        }
        //订单状态详情
        List<Map<String, Object>> orderStateDetails = orderStateDao.getOrderStateDetails(order.getId());
        for (int i = 0; i < orderStateDetails.size(); i++) {
            if (orderStateDetails.get(i).get("orderState").equals("1")) {
                orderStateDetails.get(i).put("orderNumber", "订单号：" + order.getOrderNumber());
            } else if (orderStateDetails.get(i).get("orderState").equals("2")) {
                String payType = null;
                if (order.getPayType() == 1) {
                    payType = "支付宝支付：";
                } else if (order.getPayType() == 2) {
                    payType = "微信支付：";
                } else if (order.getPayType() == 3) {
                    payType = "支付宝支付 + 红包抵扣：";
                } else if (order.getPayType() == 4) {
                    payType = "微信支付 + 红包抵扣：";
                } else {
                    payType = "红包抵扣：";
                }
                orderStateDetails.get(i).put("orderNumber", payType + order.getPayType() + "元");
            } else if (orderStateDetails.get(i).get("orderState").equals("4")) {
                orderStateDetails.get(i).put("deliveryName", "骑手：" + deliveryClerk.getName());
                orderStateDetails.get(i).put("deliveryName", "电话：" + deliveryClerk.getAccount());
            }

        }
        //订单详情
        List<Map<String, Object>> orderDetails = orderDetailsDao.findOrderDetailsByOrderNumber(orderNumber);
        map.put("orderDetails", orderDetails);
        map.put("busHeadPic", bussiness.getHeadPic());
        map.put("busName", bussiness.getBussName());
        map.put("bussTel", bussiness.getBussTel());
        map.put("busId", bussiness.getId());
        map.put("buslng", bussiness.getLng());
        map.put("buslat", bussiness.getLat());
        return map;
    }

    /**
     * 查询订单
     *
     * @param name
     * @param nameUser
     * @param orderNumber
     * @param orderState
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page queryOrder(String name, String nameUser, String orderNumber, Integer orderState, int nowPage, int pageSize) {
        return orderDao.queryOrder(name, nameUser, orderNumber, orderState, nowPage, pageSize);
    }

    /**
     * 查询订单方式
     *
     * @param orderNumber
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page<Map<String, Object>> queryOrderDetail(String orderNumber, int nowPage, int pageSize) {
        return orderDao.queryOrderDetail(orderNumber, nowPage, pageSize);
    }

    /**
     * 同意退款和拒绝退款
     *
     * @param
     * @param state
     * @param payType
     * @param reason
     * @param orderNumber @return
     * @param fee
     * @param dispatching
     * @param allMoney
     */
    @Override
    public int updateOrderState(Integer orderId, Integer state, Integer goodsId, Integer payType, Integer stock, String reason, String orderNumber, BigDecimal fee, BigDecimal dispatching, BigDecimal allMoney) throws ServiceException {
        Map<String, Object> info = orderDao.getOrderBuyerIdInfo(orderNumber);
        int userState = (int) info.get("user_state");
        if (userState == 0) {
            throw new ServiceException("该用户已经删除退款无效");
        } else if (userState == 2) {
            throw new ServiceException("该用户已经被禁用退款无效");
        }
        Order order = orderDao.getOrderMoney(orderId);
        //待付款   未付款前的取消不退款
        if (state == 1) {
            updateOrderState(OrderState.用户取消, BackOrderState.未退款, orderId);
            //用户取消  付款（没有收到货）后的取消 退款
        } else if (state == 11) {
            //1 判断支付方式
            //2 查看支付金额、订单号
            //3 取出金额返回账户（1支付宝、2微信）
            boolean isTrue = false;
            //1支付宝、2微信
            if (payType == 1) {
                isTrue = AlipayUtil.refundMoney(order.getPayOrderkid(), order.getAllMoney().doubleValue());
            } else {
                isTrue = WeixinUtils.payMallRefund(order.getPayOrderkid(), order.getAllMoney().multiply(new BigDecimal(100)).intValue(), order.getAllMoney().multiply(new BigDecimal(100)).intValue());
            }
            if (isTrue) {
                balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.退款.getCode(), order.getOrderNumber());

//                //申请退款的时候才修改库存
//                goodsDao.updateSaleNum(goodsId, stock);
                //待接单和待配送、申请退款修改状态
                updateOrderState(OrderState.用户取消, BackOrderState.未退款, orderId);
            } else {
                throw new ServiceException("退款失败，请检查订单是否存在");
            }
        } else if (state == 9) {
            // （收到货后）同意退款
            if (state > 4 && state != 12) {
                //小费加配送费
                BigDecimal money = fee.add(dispatching);
                //总金额减去小费和配送费   返回的金额
                BigDecimal backMoney = allMoney.subtract(money);
                boolean isTrue = false;
                //1支付宝、2微信
                if (payType == 1) {
                    isTrue = AlipayUtil.refundMoney(order.getPayOrderkid(), backMoney.doubleValue());
                } else {
                    isTrue = WeixinUtils.payMallRefund(order.getPayOrderkid(), backMoney.multiply(new BigDecimal(100)).intValue(), backMoney.multiply(new BigDecimal(100)).intValue());
                }
                if (isTrue) {
                    balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.退款.getCode(), order.getOrderNumber());

//                    goodsDao.updateSaleNum(goodsId, stock);
                    updateOrderState(OrderState.同意退款, BackOrderState.未退款, orderId);
                } else {
                    throw new ServiceException("退款失败，请检查订单是否存在");
                }
            } else if (state < 4 && state == 12) {
                boolean isTrue = false;
                //1支付宝、2微信
                if (payType == 1) {
                    isTrue = AlipayUtil.refundMoney(order.getPayOrderkid(), order.getAllMoney().doubleValue());
                } else {
                    isTrue = WeixinUtils.payMallRefund(order.getPayOrderkid(), order.getAllMoney().multiply(new BigDecimal(100)).intValue(), order.getAllMoney().multiply(new BigDecimal(100)).intValue());
                }
                if (isTrue) {
                    balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.退款.getCode(), order.getOrderNumber());

//                    goodsDao.updateSaleNum(goodsId, stock);
                    updateOrderState(OrderState.同意退款, BackOrderState.未退款, orderId);
                }
                //拒绝退款
            } else if (state == 10) {
                updateOrderState(OrderState.valueOfCode(order.getOrderState()), BackOrderState.拒绝退款, orderId);
                pushUserRefuse(orderNumber);
            }
        }
        return 0;
    }

    //拒绝退款的推送
    private void pushUserRefuse(String orderNumber) {
        String title = "您的申请退款已被拒绝";
        Map<String, Object> phone = orderDao.getOrderBuyerIdInfo(orderNumber);
        String tel = phone.get("account").toString();
        String name = phone.get("nick_name").toString();
        Map map = new HashedMap();
        Order order = orderDao.getOrderInfo(orderNumber);
        map.put("orderId", order.getOrderNumber());
        map.put("pushType", PushType.订单.getCode());
        map.put("orderType", order.getOrderType() + "");
        JSONObject jsonObject = JSONObject.fromObject(map);
        String data = jsonObject.toString();
        UserJPushHelper jPushHelper = new UserJPushHelper("jpush.properties");
        jPushHelper.sendByAlias("亲爱的" + name + "用户", title, data, tel, "");
    }

    /**
     * 获取商家今天收入
     *
     * @param bussId      商家编号
     * @param currentDate 当前日期
     * @return
     */
    @Override
    public Double getBussinessTodayMoney(Integer bussId, String currentDate) {
        Map<String, Object> map = orderDao.getBussinessTodayMoney(bussId, currentDate);
        Double todayMoney = ConvertTypeUtils.obj2Double(map.get("allMoney"));
        return todayMoney;
    }

    /**
     * 获取今天的订单数
     *
     * @param bussId      商家编号
     * @param currentDate 当前日期
     * @return
     */
    @Override
    public Integer getBussinessTodayOrder(Integer bussId, String currentDate) {
        Map<String, Object> map = orderDao.getBussinessTodayOrderNum(bussId, currentDate);
        Integer todayOrderNum = ConvertTypeUtils.obj2Integer(map.get("todayOrderNum"));
        return todayOrderNum;
    }

    /**
     * 取消订单
     *
     * @param orderNumber 订单单号
     * @return
     */
    @Override
    public boolean cancelOrder(String orderNumber) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (order.getOrderState().equals(OrderState.待接单.getCode()) || order.getOrderState().equals(OrderState.待付款.getCode())) {
            if (order.getReturnMoney().compareTo(BigDecimal.valueOf(0)) > 0 && order.getOrderState().equals(OrderState.待接单.getCode())) {
                returnMoney(order.getPayType(), order, OrderState.用户取消.getCode(), 0, 0);
            } else {
                User user = userService.getUserBeanById(order.getBuyerId());
                user.setRedPacket(user.getRedPacket().add(order.getRedPacketMoney()));
                userService.updateUser(user);
            }

        }
        orderDao.cancelOrder(orderNumber);
        return updateOrderState(OrderState.用户取消, BackOrderState.未退款, order.getId());
    }

    @Override
    public Map<String, Object> payOrder(String orderNumber, int payMethod, String remark) throws ServiceException {
        BigDecimal totalMoney;
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("该订单已不存在");
        }
        if (order.getOrderState() != 1) {
            throw new ServiceException("当前订单状态不允许支付");
        }
        if (remark.trim().length() > 0) {
            orderDao.updateOrderRemark(remark, order.getId());
        }
        totalMoney = order.getReturnMoney();
        String title = "订单" + order.getOrderName() + "总付款：" + totalMoney + "元";
//       String payOrderKid = "payOrder" + KidUtils.getKid();
        String payOrderKid = order.getPayOrderkid();
        Map map = new HashMap();
        if (payMethod == 1) {
            //支付宝
            //这里传的是支付订单编号
            String aplipay = AppPay.createPay(title, payOrderKid, title, totalMoney.doubleValue());
            if (order.getRedPacketMoney().compareTo(BigDecimal.valueOf(0)) > 0) {
                payMethod = 3;
            }
            orderDao.updatePayType(payMethod, order.getId());
            map.put("pay", aplipay);
        } else if (payMethod == 2) {
            //微信
            //因为微信订单编号不能重复，所以这个orderKid需要变化。
            String newPayOrderKid = "payOrder" + KidUtils.getKKid();
            if (order.getRedPacketMoney().compareTo(BigDecimal.valueOf(0)) > 0) {
                payMethod = 4;
            }
            boolean b = orderDao.updateOrderPayOrderKid(order.getId(), newPayOrderKid, payMethod) > 0;
            if (b) {
                int money = totalMoney.multiply(BigDecimal.valueOf(100)).intValue();
                map = WeixinUtils.getPayInfo(title, money, newPayOrderKid);
            } else {
                throw new ServiceException("订单发起失败");
            }

        }
        System.out.println("支付信息； 问题在哪呢" + map.toString());
        return map;
    }

    /**
     * 申请退款
     *
     * @param userId       用户编号
     * @param orderNunber  订单单号
     * @param reasonImg
     * @param reasonRefund @return
     * @throws ServiceException
     */
    @Override
    public boolean planRefundment(int userId, String orderNunber, String reasonImg, String reasonRefund) throws ServiceException {
        boolean flag = false;
        Order order = orderDao.getOrderByOrderNumber(orderNunber);
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        if (order == null) {
            throw new ServiceException("该订单不存在");
        }
//        if (order.getRefunds() != 1) {
//            throw new ServiceException("不支持退款");
//        }
        if (order.getBuyerId() != userId) {
            throw new ServiceException("您操作的不是您自己的订单");
        }
//        orderDao.updateOrderState(order.getId(), 7);
        orderDao.updateOrderApplyTime(order.getId());
        orderDao.updateReasonImgAndReasonRefund(reasonImg, reasonRefund, order.getId());
        flag = updateOrderBackState(order.getId(), BackOrderState.申请退款);
        //
//        if (bussiness.getState() != 2) {

        if (order.getOrderType() == 2) {
            //原路退款
            returnMoney(order.getPayType(), order, OrderState.同意退款.getCode(), 0, 0);
            flag = updateOrderState(OrderState.同意退款, BackOrderState.未退款, order.getId());
        }
        UserPushMsgUtil.returnMoneyOrderPushByOrderStateToBusiness(order.getId(), order.getBuyerId(), bussiness.getAccount(), orderNunber, order.getOrderType());

//        } else {
//            returnMoney(order.getPayType(), order, OrderState.同意退款.getCode(), 0, 0);
//            flag = updateOrderState(OrderState.同意退款, BackOrderState.未退款, order.getId());
//        }
        return flag;
    }

    /**
     * 计算优惠金额之后需支付金额
     *
     * @param userId 用户编号
     * @param bussId 商家编号
     * @param money  总钱数
     * @return
     */
    @Override
    public Map<String, Object> getDiscountAmount(Integer userId, Integer bussId, Double money) throws ServiceException {
        //遍历获取商家的优惠劵
        List<Map<String, Object>> couponList = couponDao.getCouponByBussId(bussId);
        Map<String, Object> map = new HashedMap();
        Double subMoney = 0.0;
        for (int i = 0; i < couponList.size(); i++) {
            Double minMoney = Double.parseDouble(couponList.get(i).get("minMoney").toString());
            if (money >= minMoney) {
                subMoney = Double.parseDouble(couponList.get(i).get("subMoney").toString());
                break;
            }
        }
        User user = userService.getUserBeanById(userId);
        map.put("subMoney", subMoney);
        if (!user.getInviteAccount().equals(null)) {
            map.put("inviteAccount", user.getInviteAccount());
        } else {
            map.put("inviteAccount", "");

        }
        map.put("money", money - subMoney);
        return map;
    }

    @Override
    public List<Map<String, Object>> getOrderStateDetail(String orderNumber) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
        List<Map<String, Object>> orderStateList;
        //骑手信息
        Integer disId = order.getDisId();
        DeliveryClerk deliveryClerk = null;
        if (disId != null) {
            deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
        }
        //订单状态详情
        orderStateList = orderStateDao.getOrderStateDetails(order.getId());

        if (orderStateList.size() >= 2) {
            if (orderStateList.get(orderStateList.size() - 2).get("orderState").toString().equals("2")) {
                Map<String, Object> map = new HashedMap();
                map.put("orderState", 999);
                map.put("backOrderState", order.getBackOrderState());
                map.put("bussTel", bussiness.getBussTel());
                map.put("created", orderStateList.get(orderStateList.size() - 2).get("created"));
                orderStateList.add(orderStateList.size() - 2, map);
            }
        }
        for (int i = 0; i < orderStateList.size(); i++) {
            orderStateList.get(i).put("refunds", order.getRefunds());
            orderStateList.get(i).put("backOrderState", order.getBackOrderState());
            orderStateList.get(i).put("bussTel", bussiness.getBussTel());
            if (orderStateList.get(i).get("orderState").toString().equals("1")) {
                orderStateList.get(i).put("orderNumber", "订单号 ：" + order.getOrderNumber());
            } else if (orderStateList.get(i).get("orderState").toString().equals("2")) {
                String payType = null;
                if (order.getPayType() == 1) {
                    payType = "支付宝支付 ：";
                } else if (order.getPayType() == 2) {
                    payType = "微信支付 ：";
                } else if (order.getPayType() == 3) {
                    payType = "支付宝支付 + 红包抵扣：";
                } else if (order.getPayType() == 4) {
                    payType = "微信支付 + 红包抵扣：";
                } else {
                    payType = "红包抵扣 ：";
                }
                orderStateList.get(i).put("orderNumber", payType + order.getAllMoney() + "元");
            } else if (orderStateList.get(i).get("orderState").toString().equals("4")) {
                if (deliveryClerk != null) {
                    orderStateList.get(i).put("deliveryName", "配送员：" + deliveryClerk.getName());
                    orderStateList.get(i).put("deliveryPhone", deliveryClerk.getAccount());
                } else {
                    orderStateList.get(i).put("deliveryName", "商家自配送：" + bussiness.getBussName());
                    orderStateList.get(i).put("deliveryPhone", bussiness.getAccount());
                }

            }

        }

        return orderStateList;
    }

    /**
     * 商家拒单
     *
     * @param id
     * @param state
     * @param buyerId
     * @param orderNumber
     * @param payType
     * @param goodsId
     * @param stock       @return
     */
    @Override
    public int refuseOrder(Integer id, Integer state, Integer buyerId, String orderNumber, String reason, Integer
            payType, Integer goodsId, Integer stock) throws ServiceException {
        Map<String, Object> info = orderDao.getOrderBuyerIdInfo(orderNumber);
        int userState = (int) info.get("user_state");
        if (userState == 0) {
            throw new ServiceException("该用户已经删除拒绝无效");
        } else if (userState == 2) {
            throw new ServiceException("该用户已经被禁用拒绝无效");
        }
        boolean a = orderDao.updateState(id, state, reason) > 0;
        Order order = orderDao.getOrderMoney(id);
        //1 判断支付方式
        //2 查看支付金额、订单号
        //3 取出金额返回账户（1支付宝、2微信）
        if (state == 8) {
            //1支付宝、2微信
            if (payType == 1) {
                AlipayUtil.refundMoney(order.getPayOrderkid(), order.getAllMoney().doubleValue());
            } else {
                WeixinUtils.payMallRefund(order.getPayOrderkid(), order.getAllMoney().multiply(new BigDecimal(100)).intValue(), order.getAllMoney().multiply(new BigDecimal(100)).intValue());
            }
        }
        if (a) {
            balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.拒绝接单.getCode(), order.getOrderNumber());
            balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getAllMoney().doubleValue(), UserBalanceState.退款.getCode(), order.getOrderNumber());
            // goodsDao.updateSaleNum(goodsId, stock);
            pushUser(buyerId, orderNumber, reason);
        } else {
            throw new ServiceException("拒单失败");
        }
        return 0;
    }

    private void pushUser(Integer buyerId, String orderNumber, String reason) {
        String title = "您的订单已被商家拒单";
        Map<String, Object> phone = orderDao.getOrderBuyerIdInfo(orderNumber);
        String tel = phone.get("account").toString();
        String name = phone.get("nick_name").toString();
        Map map = new HashedMap();
        Order order = orderDao.getOrderInfo(orderNumber);
        map.put("orderId", order.getOrderNumber());
        map.put("pushType", PushType.订单.getCode());
        //拒绝原因
        map.put("reason", reason);
        JSONObject jsonObject = JSONObject.fromObject(map);
        String data = jsonObject.toString();
        UserJPushHelper jPushHelper = new UserJPushHelper("jpush.properties");
        jPushHelper.sendByAlias("亲爱的" + name + "用户", title, data, tel, "");
    }

    /**
     * 配送员根据订单状态获取列表
     *
     * @param orderState 订单状态
     * @param dlng       配送员经度
     * @param dlat       配送员纬度
     * @param disId      配送员编号
     * @param nowPage
     * @param pageSize   @return
     */
    @Override
    public List<Map<String, Object>> getOrderListByOrderState(int orderState, Double dlng, Double dlat, int disId, int nowPage, int pageSize) throws ServiceException {
//        if (dlat == 0.0) {
//            throw new ServiceException("当前GPS信号弱请前往开阔地带");
//        }
        Map getValue = paramsService.getParamsValue(26, 24);
        Map<String, Object> map = LngLatUtil.getAround("" + dlat, "" + dlng, ConvertTypeUtils.obj2Double(getValue.get("value")));
        String maxlng = map.get("maxLng").toString();
        String minlng = map.get("minLng").toString();
        String maxlat = map.get("maxLat").toString();
        String minlat = map.get("minLat").toString();
        System.out.println("maxlat" + maxlat + "maxlng" + maxlng + "minlat" + minlat + "minlng" + minlng);
        List<Map<String, Object>> mapList = orderDao.getOrderListByOrderState(orderState, maxlng, minlng, maxlat, minlat, disId, nowPage, pageSize);
        for (int i = 0; i < mapList.size(); i++) {
            mapList.get(i).put("goods", orderDetailsDao.findOrderDetailsByOrderNumber(mapList.get(i).get("orderNumber").toString()));
        }
        return getDistance(dlng, dlat, mapList);
    }

//    @Override
//    public Map<String, Object> getOrderByOrderNumber(String orderNumber, Double dlng, Double dlat) throws ServiceException {
//        if(dlat==0.0){
//            throw  new ServiceException("当前GPS信号弱请前往开阔地带");
//        }
//       Map<String,Object> map=orderDao.getOrderByOrderInfoNumber(orderNumber);
//        double distace = Spatial4jUtil.getDistance(dlng, dlat, Double.parseDouble(map.get("lng").toString()), Double.parseDouble(map.get("lat").toString()));
//        double udistace = Spatial4jUtil.getDistance(dlng, dlat, Double.parseDouble(map.get("ulng").toString()), Double.parseDouble(map.get("ulat").toString()));
//        return null;
//    }

    /**
     * 配送员查看订单详情
     *
     * @param id   订单编号
     * @param dlng
     * @param dlat @return
     */
    @Override
    public Map<String, Object> getDeliveryOrderDetail(Integer id, Double dlng, Double dlat) throws ServiceException {
        Map<String, Object> map = new HashMap<String, Object>();
        Order order = orderDao.getOrderMoney(id);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        User user = userService.getUserBeanById(order.getBuyerId());
        double distace = Spatial4jUtil.getDistance(dlng, dlat, Double.parseDouble(bussiness.getLng()), Double.parseDouble(bussiness.getLat()));
        double udistace = Spatial4jUtil.getDistance(dlng, dlat, order.getUlng(), order.getUlat());
        BigDecimal bigDecimal = new BigDecimal(distace);
        BigDecimal ubigDecimal = new BigDecimal(udistace);
        map.put("id", id);
        map.put("dispatching", order.getDispatching());
        map.put("fee", order.getFee());
        map.put("companyHeadPic", bussiness.getHeadPic());
        map.put("headPic", user.getHeadPic());
        map.put("orderState", order.getOrderState());
        map.put("bussName", bussiness.getBussName());
        map.put("userName", order.getName());
        map.put("userAddress", order.getGoodsAdress());
        map.put("bussPhone", bussiness.getBussTel());
        map.put("userPhone", order.getReceiverPhone());
        map.put("bussLat", bussiness.getLat());
        map.put("bussLng", bussiness.getLng());
        map.put("companyAddress", bussiness.getAdress());
        map.put("userLat", order.getUlat());
        map.put("companyIsSure", order.getCompanyIsSure());
        map.put("userLng", order.getUlng());
        map.put("distace", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
        map.put("udistace", ubigDecimal.setScale(2, RoundingMode.HALF_EVEN));
        map.put("sendTime", order.getSendTime());
        if (order.getDisId() != null && !order.getDisId().equals("")) {
            map.put("disId", order.getDisId());
        } else {
            map.put("disId", 0);
        }
        if (order.getPlannedDeliveryTime() != null && !order.getPlannedDeliveryTime().equals("")) {
            map.put("isImmediate", order.getPlannedDeliveryTime());
        } else {
            map.put("isImmediate", 0);
        }
        map.put("goods", orderDetailsDao.findOrderDetailsByOrderNumber(order.getOrderNumber()));
        map.put("isRemind", reminderService.checkIsReminder(order.getId()));
        map.put("isReminderState", reminderService.checkIsReminderStatus(order.getId()));
        return map;
    }

    /**
     * 已取货
     *
     * @param id    编号
     * @param disId 配送员编号
     * @return
     */
    @Override
    public boolean pickupOrder(Integer id, Integer disId) throws ServiceException {
        Order order = orderDao.getOrderMoney(id);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!Objects.equals(order.getOrderState(), OrderState.待取货.getCode())) {
            throw new ServiceException("当前订单状态不允许取货");
        }
        return updateOrderState(OrderState.配送中, BackOrderState.valueOfCode(order.getBackOrderState()), id);
    }

    /**
     * 已送达
     *
     * @param id    编号
     * @param disId 配送员编号
     * @return
     */
    @Override
    public boolean deliveredOrder(Integer id, Integer disId) throws ServiceException {
        Order order = orderDao.getOrderMoney(id);
        DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (deliveryClerk == null) {
            throw new ServiceException("配送员不存在");
        }
        if (!Objects.equals(order.getOrderState(), OrderState.配送中.getCode())) {
            throw new ServiceException("当前订单状态不允许确认送达");
        }
        boolean flag = updateOrderState(OrderState.待评价, BackOrderState.未退款, id);
        List<Map<String, Object>> list = orderDetailsDao.getGoodsList(order.getOrderNumber());
        for (int i = 0; i < list.size(); i++) {
            int number = Integer.parseInt(list.get(i).get("count").toString());
            goodsDao.updateSaleNum(Integer.parseInt(list.get(i).get("goodsId").toString()), number);
        }

//        if (flag) {
        String blanceState = "+";
        int souceType = 1;
        orderDao.updateEndtime(id);
        //添加商家余额跟账单
        if (order.getOrderType() == 1) {
            //获取商家的信息
            Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
            UserPushMsgUtil.completedOrder(bussiness.getAccount(), order.getBussGetMoney(), order.getId(), order.getOrderNumber());
            //计算冻结金额
            Double afterMoney = MathUtils.add(bussiness.getFreezeMoney().doubleValue(), order.getBussGetMoney().doubleValue());
            //修改商家冻结金额
            businessService.updateFreezeMoney(order.getSellerId(), afterMoney);
            saveFreezeOrder(order.getOrderNumber());
            businessService.updateBussinessBalance(order.getSellerId(), order.getBussGetMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());
        }
//        else{
//            User user = userService.getUserBeanById(order.getBuyerId());
//            if (user != null) {
//                if (user.getIsCertificate() == 1) {
//                    OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(), 1);
//                    int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
//                    String goodsName = "";
//                    if (number > 1) {
//                        goodsName = orderdetail.getGoodsName() + "等多件商品";
//                    } else {
//                        goodsName = orderdetail.getGoodsName();
//                    }
//                    pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
//                            order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), order.getAllMoney(),
//                            order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
//                            order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney());
//                    rebateService.addRebate(order.getSellerId(), order.getOrderNumber(), 1);
//                }
//            }
//        }

        return saveDeliveryBlance(order, deliveryClerk, blanceState, souceType, disId);

//        }
//        return updateOrderState(OrderState.待评价, BackOrderState.未退款, id);
    }

    /**
     * 保存配送员的金额
     *
     * @param order
     * @param deliveryClerk
     * @param blanceState
     * @param souceType
     * @param disId
     * @return
     */
    private boolean saveDeliveryBlance(Order order, DeliveryClerk deliveryClerk, String blanceState, int souceType, int disId) {
        DeliveryBalance deliveryBalance = new DeliveryBalance();
        deliveryBalance.setBalance(order.getFee().add(order.getDispatching()));
        deliveryBalance.setBalanceState(blanceState);
        deliveryBalance.setCreated(new Date());
        deliveryBalance.setDeliveryId(disId);
        deliveryBalance.setSourceType(souceType);
        deliveryBalance.setOrderNumber(order.getOrderNumber());
        BigDecimal balance = deliveryClerk.getBalance() == null ? new BigDecimal(0) : deliveryClerk.getBalance();
        deliveryBalance.setCurrentAmount(balance.add(order.getFee()).add(order.getDispatching()));
        deliveryClerkService.updateDeliverBlance(disId, deliveryClerk.getBalance().add(order.getFee()).add(order.getDispatching()));
        return deliveryblancceDao.save(deliveryBalance) > 0;
    }

    /**
     * 配送员抢单
     *
     * @param disId   配送员编号
     * @param orderId 订单编号
     * @return
     * @throws ServiceException
     */
    @Override
    public Map<String, Object> grabOrder(int disId, int orderId) throws ServiceException {
        Map map = new HashedMap();
        //获取到订单对象
        Order order = orderDao.getOrderMoney(orderId);
        //对订单这个对象加同步锁
        synchronized (order) {
            if (disId == 0) {
                throw new ServiceException("配送员信息错误");
            }
            if (order == null) {
                throw new ServiceException("订单不存在");
            }
            DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(disId);
            if (deliveryClerk.getDisState() != 1) {
                throw new ServiceException("您已被禁用不能进行抢单，如有疑问请联系客服！");
            }
            //判断订单的状态
            if (!order.getOrderState().equals(OrderState.待配送.getCode())) {
                throw new ServiceException("当前订单状态不允许抢单");
            }
            boolean deliveryState = false;
            map.put("isCertificate", deliveryClerk.getIsCertificate());
            map.put("isCertification", deliveryClerk.getIsCertification());
            if (deliveryClerk.getIsCertificate().equals(0) || deliveryClerk.getIsCertificate().equals(2)) {
                return map;
            }
            //判断订单是否已经有配送员
            if (order.getDisId() == null || order.getDisId() == 0) {
                deliveryState = orderDao.updateDeliveryIdByOrderId(orderId, disId);
            }
            if (deliveryState) {
                map.put("success", updateOrderState(OrderState.待取货, BackOrderState.valueOfCode(order.getBackOrderState()), orderId));
                return map;
            } else {
                throw new ServiceException("来晚一步，订单已被其他骑手抢单");
            }
        }


    }

    /**
     * 修改订单的状态为待结单
     *
     * @param orderNumber
     * @return
     */
    @Override
    public boolean updateOrderStateByOrderNumber(String orderNumber) {
        Order order = orderDao.getOrderByPayOrderNumber(orderNumber);
        return updateOrderState(OrderState.待接单, BackOrderState.未退款, order.getId());
    }

    @Override
    public Order getOrderMoney(Integer orderId) throws ServiceException {
        Order order = orderDao.getEntityById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        return order;
    }

    @Override
    public boolean updateOrderStateByorderId(int orderId) {
        return updateOrderState(OrderState.已完结, BackOrderState.未退款, orderId);
    }

    @Override
    public List<Map<String, Object>> getOrderByIdAndTime(int orderState, int disId, int nowPage, int pageSize, String starTime, String endTime, Double dlng, Double dlat) {

        List<Map<String, Object>> mapList = orderDao.getOrderByIdAndTime(orderState, disId, nowPage, pageSize, starTime, endTime);

        return groupByDateList(getDistance(dlng, dlat, mapList), "endTime");
    }

    @Override
    public boolean updateReminderState(String orderNumber, int disId) {
        return reminderService.updateReminderState(orderNumber, disId);
    }

    /**
     * 修改订单状态
     *
     * @param orderState 订单状态
     * @param orderId    订单编号
     * @return
     */
    public boolean updateOrderState(OrderState orderState, BackOrderState backOrderState, Integer orderId) {
        OrderStates states = new OrderStates();
        states.setCreated(new Date());
        states.setOrderState(orderState.getCode());
        states.setOrderId(orderId);
        orderStateDao.save(states);
        return orderDao.updateOrderAllState(orderId, orderState.getCode(), backOrderState.getCode()) > 0;
    }

    public boolean updateOrderBackState(Integer orderId, BackOrderState backOrderState) {
        OrderStates states = new OrderStates();
        states.setCreated(new Date());
        Integer state = 0;
        //加判断
//        if (backOrderState.equals(BackOrderState.同意退款)) {
//            state = OrderState.同意退款.getCode();
//        } else
        if (backOrderState.equals(BackOrderState.拒绝退款)) {
            state = OrderState.拒绝退款.getCode();
            //应用户端没法展示地图，2017.10.30添加
            backOrderState = BackOrderState.未退款;
        } else if (backOrderState.equals(BackOrderState.申请退款)) {
            state = OrderState.申请退款.getCode();
        }
        states.setOrderState(state);
        states.setOrderId(orderId);
        orderStateDao.save(states);
        return orderDao.updateOrderBackState(orderId, backOrderState.getCode()) > 0;
    }

    /**
     * 催单查看
     *
     * @param orderId 订单编号
     * @return
     */
    @Override
    public boolean remindLook(Integer orderId) {
        return false;
    }

    public List<Map<String, Object>> getDistance(Double dlng, Double dlat, List<Map<String, Object>> mapList) {
        for (int i = 0; i < mapList.size(); i++) {
            double distace = Spatial4jUtil.getDistance(dlng, dlat, Double.parseDouble(mapList.get(i).get("lng").toString()), Double.parseDouble(mapList.get(i).get("lat").toString()));
            double udistace = Spatial4jUtil.getDistance(dlng, dlat, Double.parseDouble(mapList.get(i).get("ulng").toString()), Double.parseDouble(mapList.get(i).get("ulat").toString()));
            BigDecimal bigDecimal = new BigDecimal(distace);
            BigDecimal ubigDecimal = new BigDecimal(udistace);
            mapList.get(i).put("distace", bigDecimal.setScale(2, RoundingMode.HALF_EVEN));
            mapList.get(i).put("udistace", ubigDecimal.setScale(2, RoundingMode.HALF_EVEN));
        }
        return mapList;
    }

    /**
     * 查询配送员订单
     *
     * @param deliveryId 配送员编号
     * @param state      订单状态
     *                   1：未完成
     * @return
     */
    @Override
    public List<Map<String, Object>> findDeliveryOrderByState(Integer deliveryId, int state) {
        return orderDao.findDeliveryOrderByState(deliveryId, state);
    }

    /**
     * 同意退货
     *
     * @param orderId        订单编号
     * @param orderDetailsId
     * @return
     */
    @Override
    public boolean agreeBackGoodsOrder(Integer orderId, Integer orderDetailsId) throws ServiceException {
        Order order = orderDao.getEntityById(orderId);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (Objects.equals(order.getOrderState(), OrderState.待取货.getCode())
                || Objects.equals(order.getOrderState(), OrderState.待评价.getCode())
                || Objects.equals(order.getOrderState(), OrderState.待付款.getCode())
                || Objects.equals(order.getOrderState(), OrderState.待接单.getCode())
                || Objects.equals(order.getOrderState(), OrderState.待配送.getCode())
                || Objects.equals(order.getOrderState(), OrderState.用户取消.getCode())
//                || Objects.equals(order.getOrderState(), OrderState.货物已归还商家.getCode())
                || Objects.equals(order.getOrderState(), OrderState.配送中.getCode())) {
            throw new ServiceException("当前订单状态不允许退货");
        }
        User user = userService.getUserBeanById(order.getBuyerId());
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        if (bussiness == null) {
            throw new ServiceException("商家不存在");
        }
//        Double returnMoney = MathUtils.sub(order.getAllMoney().doubleValue(), order.getDispatching().doubleValue(), order.getFee().doubleValue());
//        Double returnBussMoney = order.getBussGetMoney().doubleValue();
//        if (returnBussMoney > bussiness.getBalance().doubleValue()) {
//            throw new ServiceException("余额不足");
//        }
        //添加商家记录并扣除余额
//        businessService.updateBussinessBalance(order.getSellerId(), order.getGoodsAllMoney().doubleValue(), CompanyBalanceState.退货.getCode(), order.getOrderNumber());
        //添加用户记录
//        balanceDetailsService.saveUserBalance(order.getBuyerId(), order.getGoodsAllMoney().doubleValue(), UserBalanceState.退货.getCode(), order.getOrderNumber());
//        orderDetailsDao.updateStatusByOrderNumber(order.getOrderNumber(), 3);
        orderDetailsDao.updateStatusByOrderDetailsId(orderDetailsId, 3);
        if (bussiness.getIsDispatching() == 1) {
            FreezeOrder freezeOrder = freezeOrderDao.getFreezeOrderByOrderNumber(order.getOrderNumber());
            Map money = getApplyReturnMoney(order);
            double returnMoney = Double.parseDouble(money.get("payMoney").toString());
            double businessReturn = Double.parseDouble(money.get("businessReturn").toString());
            double returnAllMoney = Double.parseDouble(money.get("returnAllMoney").toString());
            BigDecimal redMoney = BigDecimal.valueOf(Double.parseDouble(money.get("redPacket").toString()));
            //退款给用户(减去配送费与小费)
            //原路退款
            if (order.getGoodsAllMoney().compareTo(BigDecimal.valueOf(returnAllMoney)) == 0) {
                returnAllMoney = order.getBussGetMoney().doubleValue();
            }
            int noReturnCount = orderDetailsDao.getNoReturnCount(order.getOrderNumber());
            if (freezeOrder != null) {
                System.out.println("减少不可提现金额");
                //计算冻结金额
                Double afterMoney = MathUtils.sub(bussiness.getFreezeMoney().doubleValue(), businessReturn);
                //修改商家冻结金额
                businessService.updateFreezeMoney(order.getSellerId(), afterMoney);
                //解除冻结直接删除
                if (noReturnCount == 0) {
                    freezeOrderDao.deleteById(freezeOrder.getId());
                }
            }
//            else {
//                businessService.updateBussinessBalance(order.getSellerId(), returnAllMoney, CompanyBalanceState.退货.getCode(), order.getOrderNumber(), order.getRefunds());
//            }
//            if (order.getPayType() == 1 || order.getPayType() == 3) {
//                AlipayUtil.refundMoney(order.getPayOrderkid(), returnMoney);
//            } else if (order.getPayType() == 2 || order.getPayType() == 4) {
//                WeixinUtils.payMallRefund(order.getPayOrderkid(), (int) MathUtils.mul(returnMoney, 100D), (int) MathUtils.mul(returnMoney, 100D));
//            }
//            orderDetailsDao.updateIsReturn(order.getOrderNumber());
//            user.setRedPacket(user.getRedPacket().add(redMoney));
//            userService.updateUser(user);
        }
        String title = "您的退货商家已同意";
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("pushType", PushType.订单.getCode());
        map.put("orderNumber", order.getOrderNumber());
        JSONObject jsonObject = JSONObject.fromObject(map);
        //消息推送
        JPushUtils.sendByAlias(title, title, jsonObject.toString(), user.getAccount());
        return updateOrderState(OrderState.同意退货, BackOrderState.未退款, orderId);
    }

    /**
     * 拒绝退货
     *
     * @param orderId        订单编号
     * @param orderDetailsId
     * @return
     */
    @Override
    public boolean refuseBackGoodsOrder(Integer orderId, Integer orderDetailsId) {
        orderDetailsDao.updateStatus(orderDetailsId, 7);
        return updateOrderState(OrderState.拒绝退货, BackOrderState.未退款, orderId);
    }

    @Override
    public boolean applyReturnGoods(String orderNumber, int params, String reasonImg, String reasonRefund) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");

        }
//        if (order.getOrderState() == OrderState.待评价.getCode()) {
        Date lastTime = DateUtil.addDate(order.getCreated(), 7);
        Date nowTime = new Date();
        if (lastTime.getTime() > nowTime.getTime()) {
            orderDao.updateOrderApplyTime(order.getId());
            Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
//            orderDao.updateReasonImgAndReasonRefund(reasonImg, reasonRefund, order.getId());
            UserPushMsgUtil.applyReturnGoods(order.getId(), order.getBuyerId(), bussiness.getAccount(), orderNumber, order.getOrderType());
            return updateOrderState(OrderState.申请退货, BackOrderState.未退款, order.getId());
        } else {
            throw new ServiceException("时间超过7天不支持退货");
        }
//        } else {
//            throw new ServiceException("该状态不允许退货!");
//        }

    }

    /**
     * 确认退还货物
     *
     * @param orderId        订单编号
     * @param orderDetailsId
     * @return
     */
    @Override
    @Transactional
    public boolean sureRetunGoods(Integer orderId, Integer orderDetailsId) throws ServiceException {
        Order order = orderDao.getEntityById(orderId);
//        if (order.getDisId() != null && order.getDisId() != 0) {
//            DeliveryClerk deliveryClerk = deliveryClerkService.getDeliveryClerkById(order.getDisId());
//            //给配送员添加配送费
//            saveDeliveryBlance(order, deliveryClerk, "+", 1, order.getDisId());
//        }
        //判断冻结订单内是否存在此订单
        FreezeOrder freezeOrder = freezeOrderDao.getFreezeOrderByOrderNumber(order.getOrderNumber());
        Double returnBussMoney = order.getBussGetMoney().doubleValue();
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        //获取退换金额
        Map money = getApplyReturnMoney(order);
        double returnMoney = Double.parseDouble(money.get("payMoney").toString());
        double returnAllMoney = Double.parseDouble(money.get("returnAllMoney").toString());
        double businessReturn = Double.parseDouble(money.get("businessReturn").toString());
        BigDecimal redMoney = BigDecimal.valueOf(Double.parseDouble(money.get("redPacket").toString()));
        //退款给用户(减去配送费与小费)
        //原路退款
        int noReturnCount = orderDetailsDao.getNoReturnCount(order.getOrderNumber());
        if (noReturnCount == 0) {
            if (order.getGoodsAllMoney().compareTo(BigDecimal.valueOf(returnAllMoney)) == 0) {
                if (returnMoney - returnAllMoney > 0) {
                    returnAllMoney = order.getGoodsAllMoney().doubleValue();
                } else {
                    returnAllMoney = returnMoney;
                }
            } else if (order.getGoodsAllMoney().compareTo(BigDecimal.valueOf(returnAllMoney)) > 0) {
                if (returnMoney - returnAllMoney > 0) {
                    returnAllMoney = order.getGoodsAllMoney().doubleValue();
                } else {
                    if (redMoney.compareTo(BigDecimal.valueOf(0)) == 0) {
                        returnAllMoney = returnMoney;
                    }
                }
            }
        } else {
            if (returnMoney == 0) {
                returnAllMoney = 0;
            } else if (returnMoney - returnAllMoney <= 0) {
                returnAllMoney = returnMoney;
            }
        }
        if (freezeOrder != null) {
            System.out.println("减少不可提现金额");
            //计算冻结金额
            Double afterMoney = MathUtils.sub(bussiness.getFreezeMoney().doubleValue(), businessReturn);
            //修改商家冻结金额
            businessService.saveCompanyBalance(order.getSellerId(), businessReturn, CompanyBalanceState.退货.getCode(), order.getOrderNumber(), order.getRefunds());
            businessService.updateFreezeMoney(order.getSellerId(), afterMoney);
            //解除冻结直接删除
            if (noReturnCount == 0) {
                freezeOrderDao.deleteById(freezeOrder.getId());
            }
        } else {
            businessService.updateBussinessBalance(order.getSellerId(), businessReturn, CompanyBalanceState.退货.getCode(), order.getOrderNumber(), order.getRefunds());
        }
        if (order.getPayType() == 1 || order.getPayType() == 3) {
            AlipayUtil.refundMoney(order.getPayOrderkid(), returnAllMoney);
        } else if (order.getPayType() == 2 || order.getPayType() == 4) {
            System.out.println("微信退款：开始=======》");
            WeixinUtils.payMallRefund(order.getPayOrderkid(), (int) MathUtils.mul(order.getReturnMoney().doubleValue(), 100D), (int) MathUtils.mul(returnAllMoney, 100D));
        }
        User user = userService.getUserBeanById(order.getBuyerId());
        System.out.println("红包金额  user.getRedPacket()" + user.getRedPacket());
        System.out.println("红包金额 user.getRedPacket().add(redMoney)" + user.getRedPacket().add(redMoney));
        user.setRedPacket(user.getRedPacket().add(redMoney));
        userService.updateUser(user);
//        if (user != null) {
//            if (user.getIsCertificate() == 1) {
//                OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(), 3);
//                int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
//                String goodsName = "";
//                if (number > 1) {
//                    goodsName = orderdetail.getOrderNumber() + "的多件商品";
//                } else {
//                    goodsName = orderdetail.getGoodsName();
//                }
//                pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
//                        order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), order.getAllMoney(),
//                        order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
//                        order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney(), orderdetail.getGoodsId());
//            }
//        }
        orderDetailsDao.updateIsReturn(order.getOrderNumber());
//        returnMoney(order.getPayType(), order, OrderState.同意退货.getCode(), 0, 0);
        return updateOrderState(OrderState.货物已归还商家, BackOrderState.未退款, orderId);
    }

    /**
     * 获取退货金额
     *
     * @param order
     * @return
     */
    private Map getApplyReturnMoney(Order order) {
        Map map = new HashMap();
        //获取订单的所有金额参数
        // subMoney优惠金额    redpacketMoney红包金额 orderGoodsMoney订单记录的商品总金额 payMoney用户实际支付的现金
        BigDecimal subMoney = order.getSubMoney();
        BigDecimal redpacketMoney = order.getRedPacketMoney();
        BigDecimal orderGoodsMoney = order.getGoodsAllMoney();
        BigDecimal orderAllMoney = order.getAllMoney();
        BigDecimal payMoney = order.getReturnMoney();
        BigDecimal dispatching = order.getDispatching();
        BigDecimal fee = order.getFee();
        //查询订单详情所有商品金额   1616
        BigDecimal allGoodsMoney = orderDetailsDao.getAllMoney(order.getOrderNumber());
        //查询订单详情商家同意退货的金额  580
        BigDecimal agreeReturnMoney = orderDetailsDao.getReturnMoney(order.getOrderNumber(), 3);
        int noReturnCount = orderDetailsDao.getNoReturnCount(order.getOrderNumber());
        //判断是否是全部退货  allGoodsMoney 是否与agreeReturnMoney相同
        //所有退款金额
        double returnAllMoney = MathUtils.sub(orderAllMoney.doubleValue(), dispatching.doubleValue(), fee.doubleValue());
        //比较所有商品金额和支付商品金额判断是否参与修改价格还有满减
        BigDecimal bili;
        //如果是最后一种商品
        if (noReturnCount == 0) {
            bili = BigDecimal.valueOf(1).subtract((allGoodsMoney.subtract(agreeReturnMoney)).divide(allGoodsMoney, 2, BigDecimal.ROUND_DOWN));
        } else {
            bili = agreeReturnMoney.divide(allGoodsMoney, 2, BigDecimal.ROUND_DOWN);
        }
        if (order.getGoodsAllMoney().compareTo(allGoodsMoney) == 0) {
            //所有退款金额
            map.put("returnAllMoney", agreeReturnMoney);
            if (agreeReturnMoney.compareTo(order.getBussGetMoney()) > 0) {
                map.put("businessReturn", order.getBussGetMoney());
            } else {
                map.put("businessReturn", BigDecimal.valueOf((order.getBussGetMoney().doubleValue() * bili.doubleValue())));
            }
            double userPay = 0D;
            if (bili.compareTo(BigDecimal.valueOf(0)) > 0) {
                if (payMoney.compareTo(BigDecimal.valueOf(0)) == 0) {
                    userPay = 0;
                } else {
                    if (payMoney.compareTo(dispatching) > 0) {
                        if (payMoney.compareTo(agreeReturnMoney) > 0) {
                            userPay = agreeReturnMoney.doubleValue();
                        } else {
                            userPay = 0;
                        }
                    }
                }
            }
            if (agreeReturnMoney.doubleValue() - userPay >= 0) {
                map.put("redPacket", agreeReturnMoney.doubleValue() - userPay);
            } else {
                map.put("redPacket", 0);
            }
            map.put("payMoney", userPay);
        } else {
            if (allGoodsMoney.compareTo(agreeReturnMoney) <= 0) {
                map.put("returnAllMoney", returnAllMoney);
                map.put("businessReturn", order.getBussGetMoney());
                //排除商家修改价格，降低支付金额
                if (returnAllMoney - payMoney.doubleValue() - subMoney.doubleValue() > 0) {
                    map.put("redPacket", returnAllMoney - payMoney.doubleValue());
                } else {
                    map.put("redPacket", 0);
                }
                map.put("payMoney", payMoney);
                System.out.println("===========>>>>>退换货退还金额 returnAllMoney" + returnAllMoney + "redPacket" + (returnAllMoney - payMoney.doubleValue()) + "payMoney" + payMoney);
            } else {
                System.out.println(agreeReturnMoney + "allGoodsMoney" + allGoodsMoney);

                System.out.println("=======>>>>>>>>>>bili" + bili);
                double userPay = 0D;
                if (bili.compareTo(BigDecimal.valueOf(0)) > 0) {
                    agreeReturnMoney = BigDecimal.valueOf((returnAllMoney * bili.doubleValue()));
                    if (payMoney.compareTo(BigDecimal.valueOf(0)) == 0) {
                        userPay = 0;
                    } else {
                        if (payMoney.compareTo(dispatching) > 0) {
                            userPay = (payMoney.subtract(dispatching)).doubleValue() * bili.doubleValue();
                        } else {
                            userPay = 0;
                        }
                    }
                }
                if (agreeReturnMoney.doubleValue() - userPay >= 0) {
                    map.put("redPacket", agreeReturnMoney.doubleValue() - userPay);
                } else {
                    map.put("redPacket", 0);
                }
                if (agreeReturnMoney.compareTo(order.getBussGetMoney()) > 0) {
                    map.put("returnAllMoney", agreeReturnMoney = BigDecimal.valueOf((order.getAllMoney().doubleValue() * bili.doubleValue())));
                    map.put("businessReturn", order.getBussGetMoney());
                } else {
                    map.put("businessReturn", agreeReturnMoney = BigDecimal.valueOf((order.getBussGetMoney().doubleValue() * bili.doubleValue())));
                    map.put("returnAllMoney", agreeReturnMoney);
                }
                map.put("payMoney", userPay);
                System.out.println("退换货退还金额 returnAllMoney" + agreeReturnMoney + "redPacket" + (agreeReturnMoney.doubleValue() - userPay) + "payMoney" + userPay);
            }
        }

        return map;
    }

    @Override
    public Map<String, Object> payOrderHtml(String orderNumber, int payMethod, String remark) throws ServiceException {
        BigDecimal totalMoney;
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("该订单已不存在");
        }
        if (order.getOrderState() != 1) {
            throw new ServiceException("当前订单状态不允许支付");
        }
        if (remark.trim().length() > 0) {
            try {
                orderDao.updateOrderRemark(EmojiUtil.emojiConvert1(remark), order.getId());
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        totalMoney = order.getAllMoney();
        String title = "订单" + order.getOrderName() + "总付款：" + totalMoney + "元";
        Map map = new HashMap();
        if (payMethod == 1) {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();//创建API对应的request
            //异步回调
            alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
            alipayRequest.setReturnUrl(AlipayConfig.return_url + order.getSellerId());
            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = order.getPayOrderkid();
            //付款金额，必填
            String total_amount = order.getAllMoney().toString();
            //订单名称，必填
            String subject = order.getOrderName();
            //商品描述，可空
            String body = order.getRemark();
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            try {
                AlipayTradePagePayResponse response = alipayClient.sdkExecute(alipayRequest);
                String params = response.getBody();
//                System.out.println("请求参数"+xx);
//                System.out.println("请求"+AlipayConfig.gatewayUrl+"?"+xx);
                String sign = AlipaySignature.rsaSign(params, AlipayConfig.merchant_private_key, "utf-8", "RSA2");
                System.out.println(AlipayConfig.gatewayUrl + "?" + params + "&sign=" + sign);
                map.put("pay", AlipayConfig.gatewayUrl + "?" + params + "&sign=" + sign);
            } catch (AlipayApiException e) {
                AlipayConfig.logResult(e.getErrMsg());
                e.printStackTrace();
            }
        } else if (payMethod == 2) {
            //微信
            //因为微信订单编号不能重复，所以这个orderKid需要变化。
//            String newOrderKid =  PushType.订单.getCode() + KidUtils.getKKid();
            String newPayOrderKid = "payOrder" + KidUtils.getKKid();
            boolean b = orderDao.updateOrderPayOrderKid(order.getId(), newPayOrderKid, payMethod) > 0;
            if (b) {
                String subject = order.getOrderName();
                int money = totalMoney.multiply(BigDecimal.valueOf(100)).intValue();
                WxConfig config = null;
                //商品描述，可空
                String body = order.getRemark();
                WeixinPay weixinPay = new InstantArrivalPay();
                PayInfo payInfo = new PayInfo();
                payInfo.setBody(title);
                payInfo.setTradeNo(newPayOrderKid);
                payInfo.setSubject(title);
                payInfo.setPrice(money);
                payInfo.loadWxConfig("wxdb6448f8ce5cf029");
                weixinPay.setPayInfo(payInfo);
                map = weixinPay.createPay();
//               map = PrepareOrderInfo.createOrder(config,newPayOrderKid,subject,body,money,"","JSAPI");
//                        .getPayInfo(title, money, newPayOrderKid);
            } else {
                throw new ServiceException("订单发起失败");
            }

        }
        return map;
    }

    @Override
    public Map<String, Object> getOrderListPc(Integer orderState, Integer userId, Integer nowPage, Integer pageSize) {
        List<Map<String, Object>> orderList = orderDao.getOrderList(orderState, userId, nowPage, pageSize);
        int total = orderDao.getTotal(orderState, userId);
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).put("goods", orderDetailsDao.findOrderDetailsByOrderNumber(orderList.get(i).get("orderNumber").toString()));
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("list", orderList);
        map.put("total", total);
        return map;
    }

    @Override
    public boolean getPayState(String orderNumber) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("该订单已不存在");
        }
        int i = orderStateDao.getOrderStateByOrderNumber(order.getId());
        if (i == 1) {
            return true;
        }
        return false;
    }

    /**
     * 查询全部完成的订单数量
     *
     * @param bussId
     * @return
     */
    @Override
    public Integer getAllOrderNumber(Integer bussId) {
        return orderDao.getAllOrderNumber(bussId);
    }

    @Override
    public boolean removeOrderUserStatus(String orderNumber) {

        return orderDao.removeOrderUserStatus(orderNumber);
    }

    /**
     * 修改用户端为支付的订单金额
     *
     * @param orderNumber
     * @param money
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean updateOrderMoney(String orderNumber, Double money) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (Objects.equals(order.getOrderState(), OrderState.待付款.getCode())) {
            double chazhi = order.getGoodsAllMoney().doubleValue() - money;
            Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
            double choucheng = Double.parseDouble(bussTypeDao.getEntityById(bussiness.getBussTypeId()).getProportionate());
            double chouchngMoney = money * choucheng / 100;
            BigDecimal platformGetMoney = new BigDecimal(chouchngMoney);
            double dplatformGetMoney = platformGetMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            BigDecimal bussinessGetMoney = BigDecimal.valueOf(money).subtract(BigDecimal.valueOf(dplatformGetMoney));
            BigDecimal allMoney = order.getAllMoney().subtract(BigDecimal.valueOf(chazhi));
            BigDecimal returnMoney = order.getReturnMoney().subtract(BigDecimal.valueOf(chazhi));
            if (returnMoney.doubleValue() == 0) {
                balanceDetailsService.saveBalanceDetail(order.getOrderNumber());
                JSONObject object = JSONObject.fromObject(order);
                Map<String, String> pushMap = object;
                pushMap.put("orderType", order.getOrderType() + "");
                UserJPushHelper companyJPushHelper = new UserJPushHelper("business.properties");
                companyJPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(pushMap).build(), bussiness.getAccount());
                updateOrderState(OrderState.待接单, BackOrderState.未退款, order.getId());
                UserRedHistory userRedHistory = new UserRedHistory();
                userRedHistory.setAllMoney(order.getAllMoney());
                userRedHistory.setRedMoney(order.getRedPacketMoney());
                userRedHistory.setCreated(new Date());
                userRedHistory.setOrderNumber(orderNumber);
                userRedHistory.setType("普通订单消费");
                userRedHistoryDao.save(userRedHistory);
            } else if (returnMoney.doubleValue() < 0) {
                JSONObject object = JSONObject.fromObject(order);
                Map<String, String> pushMap = object;
                pushMap.put("orderType", order.getOrderType() + "");
                UserJPushHelper companyJPushHelper = new UserJPushHelper("business.properties");
                companyJPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(pushMap).build(), bussiness.getAccount());
                updateOrderState(OrderState.待接单, BackOrderState.未退款, order.getId());
                UserRedHistory userRedHistory = new UserRedHistory();
                userRedHistory.setAllMoney(order.getAllMoney());
                userRedHistory.setRedMoney(order.getRedPacketMoney().add(returnMoney));
                userRedHistory.setCreated(new Date());
                userRedHistory.setOrderNumber(orderNumber);
                userRedHistory.setType("普通订单消费");
                userRedHistoryDao.save(userRedHistory);
                User user = userService.getUserBeanById(order.getBuyerId());
                user.setRedPacket(user.getRedPacket().subtract(returnMoney));
                userService.updateUser(user);
                orderDao.updateRedpacketMoney(order.getOrderNumber(), order.getRedPacketMoney().add(returnMoney));
                return orderDao.updateOrderMoney(allMoney, money, platformGetMoney, bussinessGetMoney, order.getOrderNumber(), BigDecimal.valueOf(0));
            }
            return orderDao.updateOrderMoney(allMoney, money, platformGetMoney, bussinessGetMoney, order.getOrderNumber(), returnMoney);
        } else {
            throw new ServiceException("该功能只支持用户为待付款状态!");
        }

    }

    @Override
    public Map<String, Object> reservationOrder(String goods, int userId, int bussId, String bussName, String username, String goodsAddress, String phone, String remark, double allMoney, double redPacketMoney, double returnMoney, int isActivity, double subMoney) throws ServiceException {
        if (checkGoodsMoney(goods, 0)) {
            synchronized (this) {
                if (redPacketMoney > 0) {
                    User user = userService.getUserBeanById(userId);
                    if (user.getRedPacket().compareTo(BigDecimal.valueOf(redPacketMoney)) >= 0) {
                        user.setRedPacket(user.getRedPacket().subtract(BigDecimal.valueOf(redPacketMoney)));
                        userService.updateUser(user);
                    } else {
                        throw new ServiceException("红包余额不足！");
                    }
                }
            }
            userService.updateInviteAccount(userId, phone);
            Map<String, Object> map = new HashedMap();
            boolean flag = false;
            String orderKid = KidUtils.getKKid();
            String payOrderKid = "payOrder" + KidUtils.getKid();
            //创建订单
            Order order = new Order();
            //添加所有费用
            order.setAllMoney(BigDecimal.valueOf(allMoney));
            //添加商品费用
            order.setGoodsAllMoney(BigDecimal.valueOf(allMoney));
            //下单时间
            order.setCreated(new Date());
            //买家编号
            order.setBuyerId(userId);
            //配送费
            order.setDispatching(BigDecimal.valueOf(0));
            //商家编号
            order.setSellerId(bussId);
            //获取商家信息
            Bussiness bussiness = businessService.getBusinessById(bussId);
            //商家名称
            order.setOrderName(bussName);
            //支付单号
            order.setPayOrderkid(payOrderKid);
            //订单号
            order.setOrderNumber(orderKid);
            //备注
            order.setUserStatus(1);
            order.setCompanyStatus(1);
            order.setSubMoney(BigDecimal.valueOf(subMoney));
            order.setRemark(remark);
            order.setRedPacketMoney(BigDecimal.valueOf(redPacketMoney));
            order.setReturnMoney(BigDecimal.valueOf(allMoney - redPacketMoney));
            order.setIsActivity(isActivity);
            order.setOrderState(OrderState.待付款.getCode());
            order.setBackOrderState(BackOrderState.未退款.getCode());
            //收货地址
            order.setGoodsAdress(goodsAddress);
            //是否支持无理由退货
            order.setRefunds(2);
            order.setCompanyIsSure(0);
            //收货人电话
            order.setReceiverPhone(phone);
            //支付方式
            order.setPayType(0);
            order.setOrderType(2);
            double choucheng = Double.parseDouble(bussTypeDao.getEntityById(bussiness.getBussTypeId()).getProportionate());
            double chouchngMoney = allMoney * choucheng / 100;
            BigDecimal platformGetMoney = new BigDecimal(chouchngMoney);
            double dplatformGetMoney = platformGetMoney.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            //添加商家预计收入
            order.setBussGetMoney(BigDecimal.valueOf(allMoney - dplatformGetMoney));
            //添加平台抽成的钱
            order.setPlatformGetMoney(platformGetMoney.setScale(2, BigDecimal.ROUND_HALF_UP));
            //收货人
            order.setName(username);
            int orderId = (int) orderDao.save(order);
            if (orderId > 0) {
                map.put("orderKid", orderKid);
                map.put("payMoney", returnMoney);
                JSONArray jsonArray = JSONArray.fromObject(goods);
                //添加订单明细
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject object = JSONObject.fromObject(jsonArray.get(i));
                    OrderDetails orderDetails = new OrderDetails();
                    orderDetails.setCreated(new Date());
                    orderDetails.setOrderNumber(orderKid);
                    int goodsId = Integer.parseInt(object.get("goodsId").toString());
                    int number = Integer.parseInt(object.get("goodsNumber").toString());
                    orderDetails.setCount(number);
                    orderDetails.setStatus(1);
                    orderDetails.setIsReturn(0);
                    orderDetails.setGoodsId(goodsId);
                    orderDetails.setGoodsName(object.get("goodsName").toString());
                    orderDetails.setUnit(object.get("goodsUnit").toString());
                    orderDetails.setGoodsSpec(object.get("goodsSpec").toString());
                    orderDetails.setIsNoReasonReturn(Integer.parseInt(object.get("isNoReasonReturn").toString()));
                    orderDetails.setIsFree(Integer.parseInt(object.get("isFree").toString()));
                    orderDetails.setIsBespeak(Integer.parseInt(object.get("isBespeak").toString()));
                    orderDetails.setIsNoReasonReturn(Integer.parseInt(object.get("isNoReasonReturn").toString()));
                    orderDetails.setUnivalent(BigDecimal.valueOf(Double.parseDouble(object.get("goodsPrice").toString())));
                    flag = orderDetailsDao.save(orderDetails) > 0;
                    for (int goodsNum = 0; goodsNum < number; goodsNum++) {
                        ReservationOrder reservationOrder = new ReservationOrder();
                        reservationOrder.setGoodsId(goodsId);
                        reservationOrder.setOrderState(0);
                        reservationOrder.setOrderNumber(orderKid);
                        reservationOrder.setGoodsSpec(object.get("goodsSpec").toString());
                        reservationOrder.setGoodsName(object.get("goodsName").toString());
                        reservationOrder.setGoodsUnivalent(BigDecimal.valueOf(Double.parseDouble(object.get("goodsPrice").toString())));
                        reservationOrderService.saveReservationOrder(reservationOrder);

                    }
                }
                //添加完成删除购物车
                if (flag) {
                    shopCarDao.deleteShopCarByBussId(userId, bussId);
                }
                if (redPacketMoney == allMoney) {
                    balanceDetailsService.saveBalanceDetail(order.getOrderNumber());
                    UserPushMsgUtil.sumbitOrderPush(order.getId(), order.getBuyerId(), bussiness.getAccount(), order.getOrderNumber(), order.getOrderType());
                    JSONObject object = JSONObject.fromObject(order);
                    Map<String, String> pushMap = object;
                    pushMap.put("orderType", order.getOrderType() + "");
                    UserJPushHelper companyJPushHelper = new UserJPushHelper("business.properties");
                    companyJPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(pushMap).build(), bussiness.getAccount());
                    updateOrderState(OrderState.待接单, BackOrderState.未退款, orderId);
                    UserRedHistory userRedHistory = new UserRedHistory();
                    userRedHistory.setAllMoney(BigDecimal.valueOf(allMoney));
                    userRedHistory.setRedMoney(BigDecimal.valueOf(redPacketMoney));
                    userRedHistory.setCreated(new Date());
                    userRedHistory.setOrderNumber(orderKid);
                    userRedHistory.setType("预约订单消费");
                    userRedHistoryDao.save(userRedHistory);
                } else {
                    updateOrderState(OrderState.待付款, BackOrderState.未退款, orderId);
                }
            }
            return map;
        }
        return new HashedMap();
    }

    @Override
    public List<Map<String, Object>> getReservationOrderList(Integer orderState, Integer userId, Integer nowPage, Integer pageSize) {
        List<Map<String, Object>> orderList = orderDao.getReservationOrderList(orderState, userId, nowPage, pageSize);
//        orderList = EmojiUtil.returnEmojiList(orderList, "remark", "remark");
        for (int i = 0; i < orderList.size(); i++) {
//            orderList.get(i).put("goods", reservationOrderService.findReservationOrder(orderList.get(i).get("orderNumber").toString()));
            orderList.get(i).put("goods", orderDetailsDao.findOrderDetailsByOrderNumber(orderList.get(i).get("orderNumber").toString()));
        }
        return orderList;
    }

    @Override
    public Map<String, Object> getReservationOrderDetails(String orderId) throws ServiceException {
        Map map = new HashedMap();
        Order order = orderDao.getOrderByOrderNumber(orderId);
        if (order == null) {
            throw new ServiceException("该订单不存在");
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        User user = userService.getUserBeanById(order.getBuyerId());
        map.put("orderId", order.getId());
        map.put("userId", order.getBuyerId());
        map.put("companyId", order.getSellerId());
        map.put("orderNumber", order.getOrderNumber());
        map.put("companyName", order.getOrderName());
//        map.put("userName", order.getName());
        map.put("userAddress", order.getGoodsAdress());
        map.put("backOrderState", order.getBackOrderState());
        map.put("orderState", order.getOrderState());
        map.put("remark", order.getRemark());
        map.put("allMoney", order.getAllMoney());
        map.put("reason", order.getReason());
        map.put("userName", user.getNickName());
        map.put("userHeadPic", user.getHeadPic());
        map.put("orderType", order.getOrderType());
        map.put("phone", order.getReceiverPhone());
        map.put("singleReason", order.getSingleReason());
        map.put("bussGetMoney", order.getBussGetMoney());
//        map.put("phone", order.getReceiverPhone());
        map.put("created", order.getCreated());
        map.put("singleReason", order.getSingleReason());
        map.put("subMoney", order.getSubMoney());
        map.put("returnMoney", order.getReturnMoney());
        map.put("redPacketMoney", order.getRedPacketMoney());
        map.put("address", bussiness.getAdress());
        map.put("orderDetailsList", reservationOrderService.findReservationOrder(order.getOrderNumber()));

        return map;
    }

    @Override
    public List<Map<String, Object>> getOrderGoodsList(String orderNumber) {
        return orderDetailsDao.findOrderDetailsByOrderNumber(orderNumber);
    }

    @Override
    public List<Map<String, Object>> getReservationOrderListByCompanyId(Integer orderState, Integer bussId, Integer nowPage, Integer pageSize, String date, String endDate) {
        List<Map<String, Object>> orderList = orderDao.findBusinessReservationOrderByState(bussId, orderState, date, endDate, nowPage, pageSize);
        for (int i = 0; i < orderList.size(); i++) {
            orderList.get(i).put("goods", reservationOrderService.findReservationOrder(orderList.get(i).get("orderNumber").toString()));
        }
        return groupByDateList(orderList, "created");
    }

    /**
     * 预约订单
     *
     * @param userName
     * @param busName
     * @param nowPage
     * @param pageSize    @return
     * @param orderNumber
     * @param orderState
     */
    @Override
    public Page queryAppointmentOrder(String userName, String busName, int nowPage, int pageSize, String orderNumber, Integer orderState) {
        return orderDao.queryAppointmentOrder(userName, busName, nowPage, pageSize, orderNumber, orderState);
    }

    /**
     * @param orderNumber
     * @param nowPage
     * @param pageSize    @return
     */
    @Override
    public Page queryReservationOrder(String orderNumber, int nowPage, int pageSize) {
        return reservationOrderDao.queryReservationOrder(orderNumber, nowPage, pageSize);
    }


    /**
     * 商家确认送达
     *
     * @param orderNumber
     * @return
     * @throws ServiceException
     */
    @Override
    public boolean deliveredOrderByCompany(String orderNumber) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!Objects.equals(order.getOrderState(), OrderState.配送中.getCode())) {
            throw new ServiceException("当前订单状态不允许确认送达");
        }
        boolean flag = updateOrderState(OrderState.待评价, BackOrderState.未退款, order.getId());
        List<Map<String, Object>> list = orderDetailsDao.getGoodsList(order.getOrderNumber());
        for (int i = 0; i < list.size(); i++) {
            int number = Integer.parseInt(list.get(i).get("count").toString());
            goodsDao.updateSaleNum(Integer.parseInt(list.get(i).get("goodsId").toString()), number);
        }
        orderDao.updateEndtime(order.getId());
        if (order.getOrderType() == 1) {
//            User user = userService.getUserBeanById(order.getBuyerId());
//            if (user != null) {
//                if (user.getIsCertificate() == 1) {
//                    OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(), 1);
//                    int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
//                    String goodsName = "";
//                    if (number > 1) {
//                        goodsName = orderdetail.getGoodsName() + "等多件商品";
//                    } else {
//                        goodsName = orderdetail.getGoodsName();
//                    }
//                    pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
//                            order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), order.getAllMoney(),
//                            order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
//                            order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney());
//                    rebateService.addRebate(order.getSellerId(), order.getOrderNumber(), 1);
//                }
//            }
            Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
            UserPushMsgUtil.completedOrder(bussiness.getAccount(), order.getBussGetMoney(), order.getId(), order.getOrderNumber());
            //计算冻结金额
            Double afterMoney = MathUtils.add(bussiness.getFreezeMoney().doubleValue(), order.getBussGetMoney().doubleValue());
            //修改商家冻结金额
            businessService.updateFreezeMoney(order.getSellerId(), afterMoney);
            saveFreezeOrder(orderNumber);
            return businessService.saveCompanyBalance(order.getSellerId(), order.getBussGetMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());
        } else {
            return businessService.updateBussinessBalance(order.getSellerId(), order.getBussGetMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());
        }


    }

    /**
     * 保存冻结的订单
     *
     * @param orderNumber 订单编号
     * @return
     * @throws ServiceException
     */
    public boolean saveFreezeOrder(String orderNumber) throws ServiceException {
        Date now = new Date();
        FreezeOrder freezeOrder = new FreezeOrder();
        //时间加上几周
        Date freezeTime = DateUtil.addDate(now, 15);
        freezeOrder.setOrderNumber(orderNumber);
        freezeOrder.setFreezeTime(freezeTime);
        return freezeOrderDao.save(freezeOrder) > 0;
    }

    /**
     * 商家 删除订单
     *
     * @param orderNumber 订单号
     * @return
     */
    @Override
    public boolean removeOrderCompanyStatus(String orderNumber) {
        return orderDao.removeOrderCompanyStatus(orderNumber);
    }

    @Override
    public Map<Object, Object> getUserRedPacket(Integer userId) throws ServiceException {
        User user = userService.getUserBeanById(userId);
        Map<Object, Object> map = new HashMap<>();
        map.put("redPacket", user.getRedPacket());
        return map;
    }

    @Override
    public Map<Object, Object> getTrendCountAndOrderCount(Integer userId, Integer trendsId) {
        Map<Object, Object> map = new HashedMap();
        int orderCount = orderDao.getOrderCountBy(userId);
        int trendCount = trendsDao.getCountByTrendsId(trendsId);
        map.put("orderCount", orderCount);
        if (trendsId != 0) {
            map.put("trendCount", trendCount);
        } else {
            map.put("trendCount", 0);
        }

        return map;
    }

    @Override
    public int getOrderCountByDeliveryId(Integer id) {

        return orderDao.getOrderCountByDeliveryId(id);
    }

    @Override
    public boolean applyBarter(String orderNumber, int params, String barterImg, String barterRefund, int orderDetailId) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        Date lastTime = DateUtil.addDate(order.getCreated(), 15);
        Date nowTime = new Date();
        if (lastTime.getTime() > nowTime.getTime()) {
            if (order.getOrderState().equals(OrderState.已完结.getCode()) || order.getOrderState()
                    .equals(OrderState.待评价.getCode()) || order.getOrderState().equals(OrderState.同意退货.getCode())
                    || order.getOrderState().equals(OrderState.拒绝退货.getCode()) || order.getOrderState().
                    equals(OrderState.拒绝换货.getCode()) || order.getOrderState().equals(OrderState.同意换货.getCode())
                    || order.getOrderState().equals(OrderState.申请换货.getCode()) || order.getOrderState().equals(OrderState.申请退货.getCode())) {
                int number = orderStateDao.getOrderStateCount(order.getId(), OrderState.拒绝换货.getCode());
                if (number < 2) {
                    //记录商品是否申请换货
                    orderDetailsDao.updateStatus(orderDetailId, 4);
                    saveReason(barterImg, barterRefund, orderDetailId, 2);
                    orderDao.updateOrderApplyTime(order.getId());
                    orderDao.updateBarter(barterImg, barterRefund, order.getId());
                    Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
                    UserPushMsgUtil.applyReturnGoods(order.getId(), order.getBuyerId(), bussiness.getAccount(), orderNumber, order.getOrderType());
                    return updateOrderState(OrderState.申请换货, BackOrderState.未退款, order.getId());
                } else {
                    throw new ServiceException("已达申请上限，请联系在线客服！电话：4006088807！");
                }

            }
        } else {
            throw new ServiceException("时间超过7天不支持换货");
        }
        return false;
    }

    @Override
    public boolean refuseBarter(Integer orderId, Integer orderDetailsId) {
        orderDetailsDao.updateStatus(orderDetailsId, 6);
        return updateOrderState(OrderState.拒绝换货, BackOrderState.未退款, orderId);
    }

    @Override
    public boolean agreeBarter(Integer orderId, Integer orderDetailsId) {
        orderDetailsDao.updateStatus(orderDetailsId, 5);
        return updateOrderState(OrderState.同意换货, BackOrderState.未退款, orderId);
    }

    @Override
    public boolean applyReturnGoodsByOrderDetailId(String orderNumber, int orderDetailId, int params, String reasonImg, String reasonRefund) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");

        }
        Date lastTime = DateUtil.addDate(order.getCreated(), 7);
        Date nowTime = new Date();
        if (lastTime.getTime() > nowTime.getTime()) {
            if (order.getOrderState().equals(OrderState.已完结.getCode()) || order.getOrderState()
                    .equals(OrderState.待评价.getCode()) || order.getOrderState().equals(OrderState.同意退货.getCode())
                    || order.getOrderState().equals(OrderState.拒绝退货.getCode()) || order.getOrderState().
                    equals(OrderState.拒绝换货.getCode()) || order.getOrderState().equals(OrderState.同意换货.getCode())
                    || order.getOrderState().equals(OrderState.申请换货.getCode())
                    || order.getOrderState().equals(OrderState.货物已归还商家.getCode()) || order.getOrderState().equals(OrderState.申请退货.getCode())) {
                //修改申请退货时间
                orderDao.updateOrderApplyTime(order.getId());
                //添加退货原因
                saveReason(reasonImg, reasonRefund, orderDetailId, 1);

                //获取商家信息
                Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
                //记录商品是否申请退货
                orderDetailsDao.updateStatus(orderDetailId, 2);
                UserPushMsgUtil.applyReturnGoods(order.getId(), order.getBuyerId(), bussiness.getAccount(), orderNumber, order.getOrderType());
                return updateOrderState(OrderState.申请退货, BackOrderState.未退款, order.getId());
            } else {
                throw new ServiceException("该状态不允许申请退货");
            }
        } else {
            throw new ServiceException("时间超过7天不支持换货");
        }
    }

    /**
     * 查询退换货理由
     *
     * @param orderDetailsId 订单购物详情编号
     * @return
     */
    @Override
    public List<Map<String, Object>> findReasonByDetailsId(Integer orderDetailsId) {
        return orderDetailsReasonDao.findReasonByDetailsId(orderDetailsId);
    }

    /**
     * 功能描述:
     *
     * @param: 商家同意退款之后，确认归还货物
     * @return: 0未确认 1商家确认  2配送员确认
     * @auther: wsl
     * @date: 2018/11/22 10:41
     */
    @Override
    public boolean companySure(Integer orderId, Integer companyIsSure) throws ServiceException {
        Order order = orderDao.getOrderMoney(orderId);
        DeliveryClerk delivery = deliveryClerkService.getDeliveryClerkById(order.getDisId());
        UserJPushHelper jPushHelper = new UserJPushHelper("distribution.properties");
        Map<String, String> map = new HashMap<>();
        jPushHelper.sendMsgByAlias(Message.newBuilder().setMsgContent("").addExtras(map).build(), delivery.getAccount());
        return orderDao.updateCompanyIsSure(orderId, companyIsSure);
    }

    @Override
    public boolean sureGoodsSelfIntroduction(String orderNumber) throws ServiceException {
        Order order = orderDao.getOrderByOrderNumber(orderNumber);
        if (order == null) {
            throw new ServiceException("订单不存在");
        }
        if (!Objects.equals(order.getOrderState(), OrderState.等待用户自提.getCode())) {
            throw new ServiceException("请确认订单是否为自提订单");
        }
        boolean flag = updateOrderState(OrderState.待评价, BackOrderState.未退款, order.getId());
        List<Map<String, Object>> list = orderDetailsDao.getGoodsList(order.getOrderNumber());
        for (int i = 0; i < list.size(); i++) {
            int number = Integer.parseInt(list.get(i).get("count").toString());
            goodsDao.updateSaleNum(Integer.parseInt(list.get(i).get("goodsId").toString()), number);
        }
        orderDao.updateEndtime(order.getId());
        User user = userService.getUserBeanById(order.getBuyerId());
        if (user != null) {
            if (user.getIsCertificate() == 1) {
                OrderDetails orderdetail = orderDetailsDao.getGoodsByOrderNumber(order.getOrderNumber(), 1);
                int number = orderDetailsDao.getGoodsNUmberByOrderNumber(order.getOrderNumber());
                String goodsName = "";
                if (number > 1) {
                    goodsName = orderdetail.getGoodsName() + "等多件商品";
                } else {
                    goodsName = orderdetail.getGoodsName();
                }
                pensionService.savePension(order.getBuyerId(), goodsName, 1, orderdetail.getGoodsSpec(), order.getOrderNumber(),
                        order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), order.getAllMoney(),
                        order.getGoodsAllMoney().divide(BigDecimal.valueOf(100), BigDecimal.ROUND_CEILING, 3), 1,
                        order.getSellerId(), order.getPayType(), order.getGoodsAdress(), order.getRedPacketMoney(), orderdetail.getGoodsId());
                rebateService.addRebate(order.getSellerId(), order.getOrderNumber(), 1);
            }
        }
        Bussiness bussiness = businessService.getBusinessById(order.getSellerId());
        UserPushMsgUtil.selfGoodsOrderPush(bussiness.getAccount(), order.getBussGetMoney(), order.getId(), order.getOrderNumber());
        return businessService.updateBussinessBalance(order.getSellerId(), order.getBussGetMoney().doubleValue(), CompanyBalanceState.订单完成.getCode(), order.getOrderNumber(), order.getRefunds());


    }

    @Override
    public Object js(Integer orderId) {
        Order order = orderDao.getEntityById(orderId);

        getApplyReturnMoney(order);
        return new Object();
    }

    /**
     * 保存退换货等理由
     *
     * @param reasonImg     图片
     * @param reasonRefund  理由
     * @param orderDetailId 编号
     * @param type          类型 1退货  2换货
     */
    private void saveReason(String reasonImg, String reasonRefund, int orderDetailId, int type) {
        OrderDetailsReason detailsReason = new OrderDetailsReason();
        detailsReason.setReasonImg(reasonImg);
        detailsReason.setReasonRefund(reasonRefund);
        detailsReason.setType(type);
        detailsReason.setCreated(new Date());
        detailsReason.setOrderDetailsId(orderDetailId);
        orderDetailsReasonDao.save(detailsReason);
    }

}
